![](/img/trans.png)
[英]How do I grep a string on multiple files only if the string is present in all of all the files?
[英]How do I use grep to search the current directory for all files having the a string “hello” yet display only .h and .cc files?
如何使用grep在當前目錄中搜索包含字符串“hello”的任何和所有文件,並僅顯示.h和.cc文件?
grep -r --include=*.{cc,h} "hello" .
這包括:遞歸搜索(在所有子目錄中)對於包含“hello”的所有.cc或.h文件.
(當前)目錄
您可以傳入通配符,而不是指定文件名或使用stdin。
grep hello *.h *.cc
find . -name \\*.cc -print0 -or -name \\*.h -print0 | xargs -0 grep "hello"
find . -name \\*.cc -print0 -or -name \\*.h -print0 | xargs -0 grep "hello"
。
有關詳細信息,請查看find
和xargs
的手冊頁。
要以遞歸方式在當前目錄中搜索:
grep -r 'myString' .
如果我仔細閱讀你的問題,你要求“grep在當前目錄中搜索包含字符串”hello“的任何和所有文件 ,並僅顯示.h和.cc文件”。 因此,為了滿足您的精確要求,我的提交是:
這會顯示文件名:
grep -lR hello * | egrep '(cc|h)$'
...這顯示文件名和內容:
grep hello `grep -lR hello * | egrep '(cc|h)$'`
如果您需要遞歸搜索,則可以使用多種選項。 你應該考慮ack
。
如果沒有,如果你有GNU find
和xargs
:
find . -name '*.cc' -print0 -o -name '*.h' -print0 | xargs -0 grep hello /dev/null
使用/dev/null
可確保您打印文件名; -print0
和-0
處理包含空格(換行符等)的文件名。
如果你沒有笨拙的名字(有空格等),你可以使用:
find . -name '*.*[ch]' -print | xargs grep hello /dev/null
這可能會選擇一些您不想要的名稱,因為模式匹配更模糊(但更簡單),但是否則有效。 它適用於非GNU版本的find
和xargs
。
grep -l hello **/*.{h,cc}
如果沒有.h或沒有.cc文件,您可能想購買shopt -s nullglob
以避免錯誤消息。
最簡單的方法:grep -Ril“你的文字”/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.