Search code examples
bashshellgreptail

Use grep command but only for the last lines of a file?


How can I perform a grep on only the 'tail' of a file?

I am trying to run this command:

grep 'TEST COMPLETE' -L *.log

TEST COMPLETE appears in the last couple lines, this command lists all the files in the folder that have not yet finished the test (Because of -L). The logs are very big though so grep is very slow.

On the other hand I can pipe grep on the tail. The grep is pretty much instant:

tail *.log | grep 'TEST COMPLETE'

However I cannot use the -l or -L arguments as I am now grepping the pipe input and not a file. So running it with the list files argument:

tail *.log | grep 'TEST COMPLETE' -L

Will just output: (standard input)

Is there any way I can just get grep to search on the last 10 lines or something like that?


Solution

  • You can just do it in a for loop:

    for log in *.log; do
       if ! tail "$log" | grep -q 'TEST COMPLETE'; then
          echo "$log"
       fi
    done