當前位置:首頁 » 操作系統 » linuxifgrep

linuxifgrep

發布時間: 2025-02-18 14:33:50

1. Linux中使用grep命令搜索文件名及文件內容的方法

從文件中搜索並顯示文件名
當你從不止一個的文件中搜索時,默認它將顯示文件名:

復制代碼代碼如下:
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("
熱點內容
scratch少兒編程課程 發布:2025-04-16 17:11:44 瀏覽:642
榮耀x10從哪裡設置密碼 發布:2025-04-16 17:11:43 瀏覽:368
java從入門到精通視頻 發布:2025-04-16 17:11:43 瀏覽:89
php微信介面教程 發布:2025-04-16 17:07:30 瀏覽:312
android實現陰影 發布:2025-04-16 16:50:08 瀏覽:795
粉筆直播課緩存 發布:2025-04-16 16:31:21 瀏覽:348
機頂盒都有什麼配置 發布:2025-04-16 16:24:37 瀏覽:213
編寫手游反編譯都需要學習什麼 發布:2025-04-16 16:19:36 瀏覽:819
proteus編譯文件位置 發布:2025-04-16 16:18:44 瀏覽:369
土壓縮的本質 發布:2025-04-16 16:13:21 瀏覽:596