
我正在嘗試編寫一個腳本(比方說 script1.sh),該腳本在某個目錄及其子目錄中的文件中以及僅在具有某個文件的文件中查找包含我給出的單詞的行擴大。所以./script1.sh python py this.is.what.i.look.for
應該要給出這樣的結果:
python/abc/file1.py:11: this.is.what.i.look.for and the line can contain other things as well
python/file2.py:412: this.is.what.i.look.for this.toggleButton.getElement())
我嘗試使用 grep -r 在子目錄中搜尋並設法找到這些行。
grep -r -e $3 $1
給了我這些行,但未能清除具有不同文件副檔名的其他文件,並且我找不到在程式碼中包含 $2 的方法。我也未能將行號放在中間。我嘗試將輸出分成兩部分,如下所示:python/abc/file1.py:
this.is.what.i.look.for and the line can contain other things as well
withawk -F " " '{print $1}
但無法將它們重新組合在一起。我想將 grep 函數的輸出部分分配給變量,然後將它們放回一起,但也失敗了。t1="grep -r -e $3 $1 | awk -F " " '{print $1}'"
我嘗試使用「」、' '、$() 來賦值,因為我不知道該使用哪一個,但它們都不起作用。
答案1
至少對於 GNU grep
,您可以使用--include
(and --exclude
) 來限制遞歸 grep 中的匹配,使用 shell 樣式的 glob 表達式:
grep -r --include='*.py' -e pattern dir
您可以新增-n
或--line-number
新增編號。最後,記得引用位置參數 - 所以
grep -nr --include="*.$2" -e "$3" "$1"