简体   繁体   English

bash脚本在文本文件中查找模式并返回整行

[英]bash script to find pattern in text file and return entire line

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 我只需要指向正确的方向来搜索文件本身,并根据该行中的匹配返回一行

Within one dir 在一个目录内

grep "search string" *.txt

Search or go to sub-dir 搜索或转到子目录

find /full/path/to/dir -name "*.txt" -exec grep "search string" {} ;\

One slight addition. 一点点补充。 Add -n to return the line. 添加-n以返回该行。

      grep -rn "foo" *.txt 

See grep --help for more. 有关更多信息,请参阅grep --help

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 如果您还想在每次匹配时打印文件名,请将-H添加到grep

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

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