從檔案中搜尋並顯示檔案名稱
當你從不止一個的檔案中搜尋時,預設它將顯示檔案名稱:
代碼如下:
grep "word" 檔案名稱
grep root /etc/*
樣本輸出:
代碼如下:
/etc/bash.bashrc: See "man sudo_root" for details.
/etc/crontab:17 * * * * root cd / && run-parts --report /etc/cron.hourly
/etc/crontab:25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
/etc/crontab:47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
/etc/crontab:52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
/etc/group:root:x:0:
grep: /etc/gshadow: Permission denied
/etc/logrotate.conf: create 0664 root utmp
/etc/logrotate.conf: create 0660 root utmp
每行開始的第一個部分是檔案名稱(如:/etc/crontab、/etc/group)。使用 -l 選項可以只顯示檔案名稱:
代碼如下:
grep -l "string" filename
grep -l root /etc/*
樣本輸出:
代碼如下:
/etc/aliases
/etc/arpwatch.conf
grep: /etc/at.deny: Permission denied
/etc/bash.bashrc
/etc/bash_completion
/etc/ca-certificates.conf
/etc/crontab
/etc/group
你也可以逆轉輸出;使用 -L 選項來輸出那些不匹配的檔案的檔案名稱:
代碼如下:
grep -L "word" filename
grep -L root /etc/*
樣本輸出:
代碼如下:
/etc/apm
/etc/apparmor
/etc/apparmor.d
/etc/apport
/etc/apt
/etc/avahi
/etc/bash_completion.d
/etc/bindresvport.blacklist
/etc/blkid.conf
/etc/bluetooth
/etc/bogofilter.cf
/etc/bonobo-activation
/etc/brlapi.key
根據檔案內容尋找檔案
輸入以下命令:
代碼如下:
grep 'string' *.txt
grep 'main(' *.c
grep '#include' *.c
grep 'getChar*' *.c
grep -i 'ultra' *.conf
grep -iR 'ultra' *.conf
其中
-i : 忽略模式(匹配字串 valid、 VALID、 ValID )和輸入檔案(匹配 file.c FILE.c FILE.C)的大小寫。
-R : 遞迴讀取每個目錄下的所有檔案。
高亮匹配到的模式
在搜尋大量檔案的時候你可以輕鬆地高亮模式:
代碼如下:
$ grep --color=auto -iR 'getChar();' *.c
為尋找到的模式顯示檔案名稱和行號
你也許需要顯示檔案名稱和行號:
代碼如下:
$ grep --color=auto -iRnH 'getChar();' *.c
其中,
-n : 在輸出的每行前面添加以 1 開始的行號。
-H : 為每個匹配列印檔案名。要搜尋多個檔案時這是預設選項。(LCTT 譯註:-h 選項強制隱藏檔案名稱;另外 -l 和 -L 選項用於僅顯示匹配/不匹配的檔案名稱,而 -H 和 -h用於控制在顯示匹配行前顯示/不顯示檔案名稱,注意區分。)
代碼如下:
$grep --color=auto -nH 'DIR' *
輸出範例:
你也可以使用 find 命令:
代碼如下:
$ find . -name "*.c" -print | xargs grep "main("