bash grep在bash中获取匹配文本的文件名和行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10855734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep get matched text's filename and line number in bash
提问by Kyle Decot
I want to do a grepin bash on a folder searching for the term foobar. I then want to output all of the matches along w/ the filenameand line numberwhere the occurrences were found. Is this possible?
我想grep在搜索术语的文件夹上执行in bash foobar。然后我想输出所有匹配的文件名和找到出现的行号。这可能吗?
I need the output to look like:
我需要输出看起来像:
{{filename}}:{{line_number}} - {{matched_text}}
回答by Paused until further notice.
grep -nrH 'regex' /dir/
-His the option that adds filenames, -nadds line numbers, -ris recursive
-H是添加文件名、-n添加行号的选项,-r是递归的
I get filenames even without the -Hunless there's only one file.
即使没有文件名,我也会得到文件名,-H除非只有一个文件。
Add -ifor case-insensitive
添加-i不区分大小写
Add -Efor extended regular expressions
添加-E扩展正则表达式
回答by mamills
Use the -n or --line-number option
使用 -n 或 --line-number 选项
grep -n foobar
回答by Zac B
Yes; try:
grep -nr "expression" /path/to/files/
是的; 尝试:
grep -nr "expression" /path/to/files/
回答by Prince John Wesley
awkbased solution:
awk基于解决方案:
awk '/REGEX/{print FILENAME":"FNR" - "find PATH-TO-START -type f -exec awk '/REGEX/{print FILENAME":"FNR" - "##代码##}' {} \;
}' PATH
For a recursive path search,
对于递归路径搜索,
##代码##
