歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> grep 命令系列:從文件中搜索並顯示文件名

grep 命令系列:從文件中搜索並顯示文件名

日期:2017/2/28 13:54:43   编辑:Linux教程

我怎樣從幾個文件中搜索(grep),並只顯示匹配到的文件的文件名?

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

  1. grep"word"文件名
  2. grep root /etc/*

示例輸出:

  1. /etc/bash.bashrc:See"man sudo_root"for details.
  2. /etc/crontab:17**** root cd/&& run-parts --report /etc/cron.hourly
  3. /etc/crontab:256*** root test-x /usr/sbin/anacron ||(cd/&& run-parts --report /etc/cron.daily )
  4. /etc/crontab:476**7 root test-x /usr/sbin/anacron ||(cd/&& run-parts --report /etc/cron.weekly )
  5. /etc/crontab:5261** root test-x /usr/sbin/anacron ||(cd/&& run-parts --report /etc/cron.monthly )
  6. /etc/group:root:x:0:
  7. grep:/etc/gshadow:Permission denied
  8. /etc/logrotate.conf: create 0664 root utmp
  9. /etc/logrotate.conf: create 0660 root utmp

每行開始的第一個部分是文件名(如:/etc/crontab、/etc/group)。使用 -l 選項可以只顯示文件名:

  1. grep-l "string" filename
  2. grep-l root /etc/*

示例輸出:

  1. /etc/aliases
  2. /etc/arpwatch.conf
  3. grep:/etc/at.deny:Permission denied
  4. /etc/bash.bashrc
  5. /etc/bash_completion
  6. /etc/ca-certificates.conf
  7. /etc/crontab
  8. /etc/group

你也可以逆轉輸出;使用 -L 選項來輸出那些不匹配的文件的文件名

  1. grep-L "word" filename
  2. grep-L root /etc/*

示例輸出:

  1. /etc/apm
  2. /etc/apparmor
  3. /etc/apparmor.d
  4. /etc/apport
  5. /etc/apt
  6. /etc/avahi
  7. /etc/bash_completion.d
  8. /etc/bindresvport.blacklist
  9. /etc/blkid.conf
  10. /etc/bluetooth
  11. /etc/bogofilter.cf
  12. /etc/bonobo-activation
  13. /etc/brlapi.key

grep使用簡明及正則表達式 http://www.linuxidc.com/Linux/2013-08/88534.htm

正則表達式的用法 http://www.linuxidc.com/Linux/2013-03/81897.htm

正則表達式之零寬斷言 http://www.linuxidc.com/Linux/2013-03/81897.htm

Linux命令-文件文本操作grep http://www.linuxidc.com/Linux/2015-12/126259.htm

grep正則表達式 http://www.linuxidc.com/Linux/2015-09/123035.htm

Linux中正則表達式與文件格式化處理命令(awk/grep/sed) http://www.linuxidc.com/Linux/2013-03/81018.htm

Copyright © Linux教程網 All Rights Reserved