grep

本文详细介绍了grep命令的功能及其常用参数,包括如何使用正则表达式进行文本搜索,如何配置不同的输出选项如忽略大小写、显示行号等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 grep 是干什么的

  grep (缩写来自Globally search a Regular Expression and Print)是一种强大的文本搜索工具,它能使用特定模式匹配(包括正则表达式)搜索文本,并默认输出匹配行。

二 grep 语法

  grep [ -acinv ] [ -A]  [ -B ]  [ --color=auto ]  ' 查找字符串 '  filename

  参数

    -a:将binary文件已text文件的方式查找数据

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -a 'UP'
UPower

 

    -c:计算找到 “查找字符串” 的次数

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -c 'UP'
1

 

    -i:忽略大小写

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -i 'UP'
backup
centos-release-upstream
cups
cupshelpers
gnupg
group
group-
setuptool.d
updatedb.conf
UPower
wpa_supplicant

 

    -n:出处行号

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -n 'UP'
289:UPower

 

    -v:反向选择,即显示没有“查找字符串”内容的那一行

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -v 'UP'
abrt
adjtime
aliases
aliases.db
alsa
alternatives
... ...

 

    -A:后面可加数字,为after的意思,除了列出该行外,后续的 n 行 也列出来。

    -B:后面可加数字,为before的意思,除了列出该行外,前面的 n 行也列出来。

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls -al
total 2084
... ...
drwxr-xr-x    2 root  root     4096 Jun 20 02:56 udisks2
drwxr-xr-x    2 root  root     4096 Jun 20 02:55 unbound
-rw-r--r--    1 root  root      163 Jun 13 16:23 .updated
-rw-r--r--    1 root  root      557 Apr 11 04:32 updatedb.conf
drwxr-xr-x    2 root  root     4096 Jun 20 02:55 UPower
-rw-r--r--    1 root  root     1523 Apr 11 07:48 usb_modeswitch.conf
-rw-r--r--.   1 root  root       37 Oct 15  2017 vconsole.conf
-rw-r--r--    1 root  root     1982 Apr 11 07:54 vimrc
... ...

  的确如此。但是 隐藏文件并不包含在数字中。

[root@iz2ze5xd9ppdog0cch5vs0z etc]# ls | grep -A 2 -B 3 'UP' 
udisks2
unbound
updatedb.conf
UPower
usb_modeswitch.conf
vconsole.conf

 

转载于:https://www.cnblogs.com/654321cc/p/9281061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值