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?
Best Answer
|
is a shell operator, so the whole output offind
will be passed totail
. You need to run only a single command in exec by grouping all the commands to run and pass tosh
orbash
(or any shells you prefer)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 thisBut 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?