参考:
《跟老男孩学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