I am trying to find all files that start with a certain name, then go through each file to find lines that contains a string, then only print out the last line of each file that contain the string. Step by step, I first find all files in my directory that start with "A123"

find . -name 'A123*'

then get each line in the file that contains "Trial"

find . -name 'A123*' -exec grep 'Trial' {} \;

and then from here I only want to print the last line,

find . -name 'A123*' -exec grep 'Trial' {} | tail -1 \;

however, this last command does not work. How do I fix this to get what I am trying to get?

1 Answer 1


| is a shell operator, so the whole output of find will be passed to tail. You need to run only a single command in exec by grouping all the commands to run and pass to sh or bash (or any shells you prefer)

find . -name 'A123*' -exec bash -c 'grep Trial "$1" | tail -1' grep {} \;

Or you can just use some other single commands for getting the last match from How to grep the last occurrence of a line pattern

If you can make sure that you files contain no special characters like #$/\`&*~-... in their names you can use this

find . -name 'A123*' -exec bash -c "grep 'Trial' {} | tail -1" \;

But please be aware that strange things may happen there when there are unexpected names you didn't know. For more information read Is it possible to use find -exec sh -c safely?


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .