grep基本学习

参考:

《跟老男孩学Linux运维:核心系统命令实战》 

在线bash:https://c.runoob.com/compile/18

实现or,and,not:https://www.jianshu.com/p/4ec50fdaf388

 

grep: global search regular expression(RE) and print out the line

注意学习几个参数的含义

  • 不加参数,显示匹配的行,起到搜索作用
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt
grep "o" test.txt

输出为:   hello; world;ni; hao 

  • -v 显示不匹配的行,起到排除的作用
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt
grep -v "o" test.txt

输出为:

chen;pan;   this
xie; juan 

  • -n 显示匹配的行,并且加上行号,起到查询作用,当匹配内容为正则表达式".",则会对所有行加上行号输出
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt
grep -n "o" test.txt

输出为:

1:   hello; world;ni; hao

  • -i 不区分大小写
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt
grep -i "X" test.txt

输出为:xie; juan

  • -E 使用扩展的egrep,将匹配模式延伸为正则表达式使用
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt

grep "x\|c" test.txt
grep -E "x|c" test.txt
egrep "x|c" test.txt
grep -e "x" -e "c" test.txt

四种写法一样,结果都是:

chen;pan;   this
xie; juan

  • -c 只计算匹配的行数(注意不是匹配次数)
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt

grep -c "x\|c" test.txt

输出结果为:2

--color[=WHEN]为匹配处的字符串添加颜色,可选的为auto, always, never

echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt

grep --color=always "x\|c" test.txt

输出为:(在线bash)

[01;31m[Kc[m[Khen;pan;   this
[01;31m[Kx[m[Kie; juan

  • -w 只输出含有整个单词的行
echo '   hello; world;ni; hao
chen;pan;   this
xie; juan' > test.txt

grep -w "xi" test.txt
echo "-----------"
grep -w "xie" test.txt

输出为:

-----------
xie; juan

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值