Ubuntu-18.04.6 中的「grep」指令有什麼問題?

Ubuntu-18.04.6 中的「grep」指令有什麼問題?

我喜歡「grep」幾十年了,但幾年後我離開了 Linux,當我再次回來時,發現「grep」的工作方式與以前不同。我從網上檢查了它的使用情況並確認我的內存沒有損壞。

我確信有些*.h文件*.cpp位於更深的子目錄下。我使用了下面的命令並得到了意想不到的類似結果:

grep 44738 -r -l *.h
grep 44738 -r -l *.c
grep 44738 -r -l *.c*

我得到的結果是

 grep: *.h: No such file or directory
 ./daemons/snmpcd/snmpcd.cpp
 ./.svn/pris.......svn-base

 grep: *.c: No such file or directory
 ./daemons/snmpcd/snmpcd.cpp
 ./.svn/pris.......svn-base

 grep: *.c*: No such file or directory
 ./daemons/snmpcd/snmpcd.cpp
 ./.svn/pris........svn-base

分別。

  • 如果我使用命令:grep 44738 -r -l .,除了第一行之外,我得到相同的結果grep: ...
  • 如果我使用指令:grep 44738 -r -l *.c*,我就grep: ...沒有任何文件。
  • 如果我使用指令:grep 44738 -r -l -file *.c* .,我就得到了grep: *.c*: No such file or directory

這個結果幾乎與我幾年前的經歷相反。我的問題是:

  1. ubuntu-18.04.6 有很多變化嗎grep
  2. 如何在 grep 中指定檔案模式?為什麼我不能像幾年前那樣使用*.c像那樣的模式?*.h *.c*
  3. 我的同事建議我使用ack,但我發現幾乎一樣的事情。我應該像以前一樣使用哪些命令進行全域字串搜尋grep

答案1

這裡有兩個問題。首先,您不能組合-r-R標誌並同時將目標檔案名稱作為參數給出。-r/打開遞歸搜索-R,這意味著“搜索給定目錄中的所有文件”,因此它們會將其grep參數視為在其中查找文件的目錄。*.c*。據我記憶,情況一直如此,至少從我使用 Linux 到現在已經接近 25 年了。

如果不使用-r/-R標誌,您可以根據需要使用 glob,你必須引用它們,這是至關重要的。如果你不引用它,就像你所做的那樣,glob將被shell擴展為任何匹配的文件,並且grep不會看到glob,而只能看到shell擴展它的結果,因此只能看到glob中的任何檔案或目錄名稱與 glob 相符的目前目錄。

現在,GNU(grepLinux 上的預設設定)有一種方法可以完成您想要的操作,但語法不同:

grep 44738 -r -l --include='*.h'

man grep

  --include=GLOB
          Search only files whose base name matches GLOB (using  wildcard
          matching  as  described  under  --exclude).   If  contradictory
          --include and --exclude options are given,  the  last  matching
          one  wins.   If no --include or --exclude options match, a file
          is included unless the first such option is --include.

相關內容