简体   繁体   中英

Which file is grep searching?

Suppose I'm grepping multiple files, is there a way to display which file grep is currently searching?

Ex:

grep "*.log" file1 file2 file3 file4

Is it possible to determine which file is currently being searched, ie file1, file2, file3, etc., by grep and display this output?

Thanks!

As discussed over in the comments, grep has the option -H for this. From the man page,

   -H, --with-filename
          Print the file name for each match.  This is the default when there is more than one file to search.

All you need to do is add the flag in your command as grep -H "*.log" file1 file2 file3 file4 and you can observe the order in which grep does the pattern matching in each of the input files.

If grep is not displaying any matches, and you want to know which file it is currently scanning, you might want to examine the file handles it has open. This isn't portable, but on Linux, it appears that file descriptor 3 will be the one you want to examine, which you can do with

ls -l /proc/1234/fd/3

where 1234 is the PID of the grep process.

You can use a simple loop and globstar to run over all files and echo the name and then grep for your pattern.

for file in **
do
  echo "searching $file"
  grep "$pattern" "$file"
done

This will display the results as:

searching file1 
LINE_WITH_PATTERN 
searching file2 
searching file3
LINE2_WITH_PATTERN

If you only want to search specific file ...

for file in file1 file2 file3 file4

Using --with-filename is certainly the easier way to associate results with the file containing the result, but if you really want to see which file grep is currently searching you can simply call it in a loop:

for f in file1 file2 file3 file4; do
  echo "Searching $f"
  grep "*.log" "$f"
done

This will print the filename before it's search begins.

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