linux 三剑客之 grep 命令

1740阅读 0评论2021-05-24 iibull
分类:其他平台

grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

点击(此处)折叠或打开

  1. [root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
  2. 选项与参数:
  3. -a :将 binary 文件以 text 文件的方式搜寻数据
  4. -c :计算找到 '搜寻字符串' 的次数
  5. -i :忽略大小写的不同,所以大小写视为相同
  6. -n :顺便输出行号
  7. -v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
  8. --color=auto :可以将找到的关键词部分加上颜色的显示喔!

点击(此处)折叠或打开

  1. # dmesg | grep -n -A3 -B2 --color=auto 'eth'
  2. 用 dmesg 列出核心信息,再以 grep 找出内含 eth 那行,在关键字所在行的前两行与后三行也一起捉出来显示

  3. # grep -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件
  4. # grep -l -r ‘energywise’ * #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件

  5. 使用正则表达式
  6. # grep -n 't[ae]st' regular_express.txt
  7. 需要的字串是『tast』或『test』两个字串

  8. # grep -n '[^g]oo' regular_express.txt
  9. 想要搜索到有 oo 的行,但不想要 oo 前面有 g

  10. # grep -n 'o\{2\}' regular_express.txt
  11. 要找到两个 o 的字串


  12. # grep -n 'go\{2,5\}g' regular_express.txt
  13. 要找出 g 后面接 2 到 5 个 o ,然后再接一个 g 的字串


点击(此处)折叠或打开

  1. 扩展grep(grep -E 或者 egrep)
  2. 对于标准grep,如果在扩展元字符前面加\,grep会自动启用扩展选项-E。

  3. # egrep 'NW|EA' testfile
  4. 打印所有包含NW或EA的行

  5. # egrep '3+' testfile
  6. # grep -E '3+' testfile
  7. # grep '3\+' testfile
  8. 搜索所有包含一个或多个3的行。


  9. # egrep '2\.?[0-9]' testfile
  10. # grep -E '2\.?[0-9]' testfile
  11. # grep '2\.\?[0-9]' testfile
  12. #首先含有2字符,其后紧跟着0个或1个点,后面再是0和9之间的数字。


  13. # egrep '(no)+' testfile
  14. # grep -E '(no)+' testfile
  15. # grep '\(no\)\+' testfile #3个命令返回相同结果,




上一篇:Linux三剑客之awk命令
下一篇:tcpdump 对网络上的数据包进行截获的包分析工具