简体   繁体   English

grep搜索哪个文件?

[英]Which file is grep searching?

Suppose I'm grepping multiple files, is there a way to display which file grep is currently searching? 假设我要grep多个文件,有没有办法显示grep当前正在搜索哪个文件?

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? 是否可以确定grep当前正在搜索哪个文件,即file1,file2,file3等,并显示此输出?

Thanks! 谢谢!

As discussed over in the comments, grep has the option -H for this. 如注释中所述, grep为此提供了-H选项。 From the man page, man页中

   -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. 您需要做的就是在命令中将标志添加为grep -H "*.log" file1 file2 file3 file4 ,您可以观察grep在每个输入文件中进行模式匹配的顺序。

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. 如果grep没有显示任何匹配项,并且您想知道它当前正在扫描哪个文件,则可能要检查它已打开的文件句柄。 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 这不是可移植的,但是在Linux上,似乎文件描述符3是您要检查的文件描述符,您可以使用

ls -l /proc/1234/fd/3

where 1234 is the PID of the grep process. 其中1234grep进程的PID。

You can use a simple loop and globstar to run over all files and echo the name and then grep for your pattern. 您可以使用简单的循环和globstar来运行所有文件,并回显名称,然后使用grep表示您的模式。

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: 使用--with-filename当然是将结果与包含结果的文件相关联的更简单方法,但是如果您真的想查看grep当前正在搜索哪个文件,则可以在循环中简单地调用它:

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. 这将在搜索开始之前打印文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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