![](/img/trans.png)
[英]Using grep to recursively search through subdirectories for specific keyword inside specific filename
[英]Using “grep” to search for specific type of files in all subdirectories
我試圖在包含很多子目錄的目錄中的包含“ Mutual_Values_23.0”的文件中找到特定行。 我知道此行號存儲在以“ gnuout_mutual _.... txt”開頭的文件中(文件名的省略號部分是時間戳,因此會有所不同)。
我想知道是否有一種方法可以指定“ grep”命令以僅針對以“ gnuout_mutual _.... txt”開頭的文件查看子目錄。
我努力了
grep -r "Mutual_Values_23.0" *
但這要花很長時間
使用find
在所有子目錄中搜索帶有搜索字符串“ Mutual_Values_23.0”的“ gnuout ... txt”文件
find . -mindepth 1 -name gnuout_mutual_\*.txt -type f -exec grep "Mutual_Values_23.0" {} +
您可以使用以下grep選項:
--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
對於行號,您應該使用-n
選項。 在要查找的文件夾的根目錄中,可以使用以下最終命令:
grep -nr "Mutual_Values_23.0" --include="gnuout_mutual_*txt"
如果使用bash ,則可以使用globstar選項:
globstar
如果已設置,則在路徑名擴展上下文中使用的模式**
將匹配所有文件以及零個或多個目錄和子目錄。 如果模式后跟/
,則僅目錄和子目錄匹配。
因此,您可以像這樣使用它:
$ shopt -s globstar
$ grep "search_string" **/glob-pattern
或對於OP:
$ shopt -s globstar
$ grep Mutual_Values_23.0 **/gnuout_mutual_*.txt
GNU grep具有--include GLOB
選項,其中GLOB
可用於指定您需要匹配的文件名模式。
grep -rn --include 'gnuout_mutual_*txt' 'Mutual_Values_23.0' .
使用此命令:
$ find . -name "*Mutual_Values_23.0*"
注意:在要搜索文件集的目錄中運行此命令。
希望能有所幫助,加油!
您可以使用find
搜索文件並將結果傳遞給grep。
find /directory_where_to_search/ -iname 'gnuout_mutual_*.txt' | xargs grep 'Mutual_Values_23.0' -sl
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.