您好,欢迎来到思海网络,我们将竭诚为您提供优质的服务! 诚征网络推广 | 网站备案 | 帮助中心 | 软件下载 | 购买流程 | 付款方式 | 联系我们 [ 会员登录/注册 ]
促销推广
客服中心
业务咨询
有事点击这里…  531199185
有事点击这里…  61352289
点击这里给我发消息  81721488
有事点击这里…  376585780
有事点击这里…  872642803
有事点击这里…  459248018
有事点击这里…  61352288
有事点击这里…  380791050
技术支持
有事点击这里…  714236853
有事点击这里…  719304487
有事点击这里…  1208894568
有事点击这里…  61352289
在线客服
有事点击这里…  531199185
有事点击这里…  61352288
有事点击这里…  983054746
有事点击这里…  893984210
当前位置:首页 >> 技术文章 >> 文章浏览
技术文章

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

添加时间:2016-2-16 19:28:04  添加: 思海网络 
从文件中搜索并显示文件名
当你从不止一个的文件中搜索时,默认它将显示文件名:

代码如下:
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<example.h>' *.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("


关键字:Linux、grep、命令
分享到:

顶部 】 【 关闭
版权所有:佛山思海电脑网络有限公司 ©1998-2024 All Rights Reserved.
联系电话:(0757)22630313、22633833
中华人民共和国增值电信业务经营许可证: 粤B1.B2-20030321 备案号:粤B2-20030321-1
网站公安备案编号:44060602000007 交互式栏目专项备案编号:200303DD003  
察察 工商 网安 举报有奖  警警  手机打开网站