简体   繁体   中英

Search only last n lines of a file for matching text pattern and print filenames that do not have this pattern

I would like to search the last 2 lines of a bunch of similarly named files for a given text pattern and write out the filenames where matches are NOT found.

I tried this:

tail -n 2 slurm-* | grep -L "run complete"

As you can see "slurm" is the file base, and I want to find files where "run complete" is absent. However, this command does not give me any output. I tried the regular (non-inverse) problem:

tail -n 2 slurm-* | grep -H "run complete"

and I get a bunch of output (all the matches that are found but not the filenames):

(standard input):run complete

I figure that I have misunderstood how piping tail output to grep works, any help is greatly appreciated.

This should work -

for file in `ls slurm-*`;
do
res=`tail -n2 $file | grep "run complete" 1>/dev/null 2>&1; echo $?`;
  if [ $res -ne 0 ];
  then
    echo $file ;
  fi ;
done ;

Explanation -

"echo $?" gives us the return code of the grep command. If grep finds the pattern in the file, it returns 0. Otherwise the return code is non-zero.

We check for this non-zero return code, and only then, "echo" the file name. Since you have not mentioned whether the output of grep is necessary, I have discarded the STD_OUT and STD_ERR by sending it to /dev/null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM