Linux bash脚本在文本文件中查找模式并返回整行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5655713/
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
bash script to find pattern in text file and return entire line
提问by Sally Sasquatch
I need to make a bash script which loops through a bunch of .txt files in a directory, then searches each .txt for a string, and returns the entire line that string appears on
我需要制作一个 bash 脚本,它循环遍历目录中的一堆 .txt 文件,然后在每个 .txt 中搜索一个字符串,并返回该字符串出现的整行
I know how to look through all the .txt files in the directory,
我知道如何查看目录中的所有 .txt 文件,
I just need to be pointed in the right direction for searching the file itself, and returning a line based on a match in that line
我只需要指向正确的方向来搜索文件本身,并根据该行中的匹配返回一行
回答by amit_g
Within one dir
一个目录内
grep "search string" *.txt
Search or go to sub-dir
搜索或转到子目录
find /full/path/to/dir -name "*.txt" -exec grep "search string" {} ;\
回答by Matt
you can use a loop:
您可以使用循环:
for i in $(find|grep .txt); do grep "search" "$i";
If you also want to print the filename with each match, add -H
to grep
for i in $(find|grep .txt); do grep "search" "$i";
如果您还想打印每个匹配项的文件名,请添加-H
到 grep
回答by Bryan
One slight addition. Add -n
to return the line.
一点点补充。添加-n
以返回行。
grep -rn "foo" *.txt
See grep --help
for more.
查看grep --help
更多。