❏ 站外平台:

grep 命令系列:从文件中搜索并显示文件名

作者: Vivek Gite 译者: LCTT Xingyu.Wang

| 2016-01-30 14:16   收藏: 2    

我怎样从几个文件中搜索(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:25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
  4. /etc/crontab:47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
  5. /etc/crontab:52 6 1 * * 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

via: http://www.cyberciti.biz/faq/grep-from-files-and-display-the-file-name/

作者:Vivek Gite 译者:wxy 校对:wxy

本文由 LCTT 原创编译,Linux中国 荣誉推出



最新评论

从 2025.1.15 起,不再提供评论功能
LCTT 译者
Xingyu.Wang 💎💎💎
共计翻译: 995.0 篇 | 共计贡献: 3546
贡献时间:2014-07-25 -> 2024-04-09
访问我的 LCTT 主页 | 在 GitHub 上关注我


返回顶部

分享到微信

打开微信,点击顶部的“╋”,
使用“扫一扫”将网页分享至微信。