歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Linux中使用grep命令搜索文件名及文件內容的方法

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

日期:2017/3/2 16:25:59   编辑:Linux服務器

  從文件中搜索並顯示文件名

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

  代碼如下:

  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' *

  輸出樣例:

201625112508116.png (530×158)

  你也可以使用 find 命令:

  代碼如下:

  $ find . -name "*.c" -print | xargs grep "main("

Copyright © Linux教程網 All Rights Reserved