cwd*_*cwd 5 command-line grep bash ubuntu locate
我试图找到check_dns在nagios'commands.cfg文件中定义的位置,尽管有很多文件。
我知道我可以运行类似find / -name "command.cfg" -exec grep check_dns {} \;搜索匹配的东西,但如果可能的话,我想使用locate它,因为它是一个索引副本,而且速度要快得多。
当我运行时,locate commands.cfg我得到以下结果:
/etc/nagios3/commands.cfg
/etc/nagiosgrapher/nagios3/commands.cfg
/usr/share/doc/nagios3-common/examples/commands.cfg
/usr/share/doc/nagios3-common/examples/template-object/commands.cfg
/usr/share/nagiosgrapher/debian/cfg/nagios3/commands.cfg
/var/lib/ucf/cache/:etc:nagiosgrapher:nagios3:commands.cfg
Run Code Online (Sandbox Code Playgroud)
是否可以运行 locate 并将其通过管道传递给内联命令之类的xargs,以便我可以获得grep每个结果?我意识到这可以通过 for 循环来完成,但我希望在这里找到一些 bash-fu / shell-fu,而不是如何针对这种特定情况进行操作。
是的,您可以xargs为此使用。
例如一个简单的:
$ locate commands.cfg | xargs grep check_dns
Run Code Online (Sandbox Code Playgroud)
(当grep看到多个文件时,它会在每个文件中搜索并启用匹配项的文件名打印。)
或者您可以通过以下方式显式启用文件名打印:
$ locate commands.cfg | xargs grep -H check_dns
Run Code Online (Sandbox Code Playgroud)
(以防万一只grep用 1 个参数调用一个by xargs)
对于只接受一个文件名参数(不同于grep)的程序,您可以像这样限制提供的参数数量:
$ locate commands.cfg | xargs -n1 grep check_dns
Run Code Online (Sandbox Code Playgroud)
这不会打印匹配行来自的文件的名称。
结果相当于:
$ locate commands.cfg | xargs grep -h check_dns
Run Code Online (Sandbox Code Playgroud)
使用现代的 locate/xargs,您还可以防止空格问题:
$ locate -0 commands.cfg | xargs -0 grep -H check_dns
Run Code Online (Sandbox Code Playgroud)
(默认情况下,空格分隔输入xargs- 当您的文件名包含空格时,这当然是一个问题......)
| 归档时间: |
|
| 查看次数: |
1058 次 |
| 最近记录: |