我在一个目录中有许多日志文件。我正在尝试编写一个脚本来在所有日志文件中搜索一个字符串并回显文件名和找到该字符串的行号。
我想我可能不得不使用 2 个 grep - 将一个的输出通过管道传输到另一个,因为 -l 选项只返回文件名而不返回行号。任何有关如何成功实现这一目标的见解都将不胜感激。
非常感谢,
亚历克斯
最佳答案
$ grep -Hn root /etc/passwd
/etc/passwd:1:root:x:0:0:root:/root:/bin/bash
结合 -H
和 -n
可以达到您的预期。
如果你想在没有字符串的情况下回显所需的信息:
$ grep -Hn root /etc/passwd | cut -d: -f1,2
/etc/passwd:1
或使用 awk :
$ awk -F: '/root/{print "file=" ARGV[1] "\nline=" NR}' /etc/passwd
file=/etc/passwd
line=1
如果你想创建 shell
变量:
$ awk -F: '/root/{print "file=" ARGV[1] "\nline=" NR}' /etc/passwd | bash
$ echo $line
1
$ echo $file
/etc/passwd
关于linux - Grep - 返回文件的行号和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462979/