grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来
grep的一些常用参数如下:
-n 打印行号grep -n ".*" h.txt 所有打印行号grep -n "root" h.txt 匹配的内容显示行号-v 不包括-E 表示过滤 多个参数grep -Ev "sshd|network|crond|sysstat|"-o:仅打印你需要的东西,默认打印正行grep -o "hello" h.txt-i:忽略大小写grep -i "hello" h.txt-c: 用于统计文中出现的次数-A:后面紧跟一数字,如-A1表示打印出符合要求的行及其下一行-B:后面紧跟一数字,如-B1表示打印出符合要求的行及其上一行-C:后面紧跟一数字,如-C1表示打印出符合要求的行及其上下各一行
linux中的一些正则用法,也是今天用到的。
^ #锚定行的开始 如:'^samp'匹配所有以sam开头的行。$ #锚定行的结束 如:'sam$'匹配所有以sam结尾的行。. #匹配一个非换行符的字符 如:'s.m'匹配sXm,其中X为任意一个字符。.* #代表任意字符。
举例来看。
我们的test.txt文件内的内容为:
hello world!world hello!hello nihao!gui tt!
当我们想要找到hello开头的行时:
grep "^hello" test.txt
最终的输出为
hello world!hello nihao!
当我们只想要不含hello的行时
grep -v "hello" test.txt
最终输出为:
gui tt!
当我们既想要以hello开头同时又含有world的行时:
grep "^hello" test.txt|grep "world"
最终的输出为:
hello world!
当我们想要含有nihao及其上下各一行时:
grep -C1 "nihao" test.txt
最终输出为
world hello!hello nihao!gui tt!
关于linux的往期精彩:
linux命令一:cd
linux命令二:ls命令
linux命令之cp, rm, mv
前天晚上临睡前一个大学同学突然联系了我
linux中几个和文件相关的命令
不会用vi,还好意思说自己是个程序猿?
linux shell中的一些命令
![bf9d1e92e03df0fa7d451b9eb1a47fab.png](https://img-blog.csdnimg.cn/img_convert/bf9d1e92e03df0fa7d451b9eb1a47fab.png)