How to find the last match of a string in a bunch of files

8,427

Use tail -n 1 in a for loop. For example:

for name in *.file; do
    grep -H text "$name" | tail -n 1
done

(The -H option will make grep always print the file name, even if only one file was given.)

Share:
8,427

Related videos on Youtube

Joe
Author by

Joe

I’m Joe. I have interests that include Disability, Creative Writing, Open data and Computer Science. I’m contactable at [email protected]. My github profile is at: https://github.com/joereddington

Updated on September 18, 2022

Comments

  • Joe
    Joe over 1 year

    I have a bunch of files, I'd like to find the last match of a string in each of them.

    grep text *.file gives me all the matches not the last ones.

    ls *.file | xargs grep text | tail -n 1 gives me the last line of the last file that matches.

    So what I think I want is a way to say:

    ls *.file | (xargs grep text | tail -n 1)
    

    But I'm not sure how to do this, or if it's possible.

  • jvriesem
    jvriesem almost 4 years
    +1 for the -H option.