grep命令使用与正则表达式搜索

grep(global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。Linux自带这个命令,查找文本内容的时候非常方便。

常用命令选项

以下列出一些常用选项,需要更多帮助可以输入:grep --help进行查看。

  • -A 后面可加数字,为 after 的意思,除了列出该行外,后续的 n 行也列出来;
  • -B 后面可加数字,为 befer 的意思,除了列出该行外,前面的 n 行也列出来;
  • -E 将范本样式为延伸的普通表示法来使用,意味着使用能使用扩展正则表达式。
  • -i 忽略字符大小写的差别。
  • -n 在显示符合范本样式的那一列之前,标示出该列的编号。
  • -v 反转查找。
  • -o 只输出文件中匹配到的部分。

正则表达式

下面是一些正则表达式中常用的特殊符号

  • [:alnum:] - 字母数字字符
  • [:alpha:] - 字母字符
  • [:blank:] - 空字符: 空格键符 和 制表符
  • [:digit:] - 数字: '0 1 2 3 4 5 6 7 8 9'
  • [:lower:] - 小写字母: 'a b c d e f g h i j k l m n o p q r s t u v w x y z'
  • [:space:] - 空格字符: 制表符、换行符、垂直制表符、换页符、回车符和空格键符
  • [:upper:] - 大写字母: 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'

下面是正则表达式中常用的元字符:

  • [] 匹配一个指定范围内的字符,[] 里面不论有几个字节,他都谨代表某『一个』字节
  • ^ 行首,那个 ^ 符号,在字节集合符号(括号[])之内与之外是不同的! 在 [] 内代表『反向选择』,在 [] 之外则代表定位* 在行首的意义!要分清楚喔!
  • $ 行尾
  • . (小数点):代表『一定有一个任意字节』的意思;
  • * (星星号):代表『重复前一个字节, 0 到无穷多次』的意思,为组合形态,注意和bash中的*意义不同啊
  • {} 字符范围,如2-5{2,5},在shell中{}有特殊含义需要用来转义,比如这样{}
  • () 将一个或多个字符捆绑在一起,当做一个整体进行处理,反向引用照常使用。
  • |

举例说明

网上随便找了一段英文来测试,请用vi 1.txt新建文本并写入以下内容:

Do you charge for stopped instances?
Yes, instances in a stopped state continue to reserve dedicated system resources (RAM, SSD storage, IP aliases, CPU) and therefore incur charges until you destroy the instance.
If you wish to no longer accumulate charges for a virtual machine, please use the DESTROY button in the customer portal.

最简单直接的用法,找出含有'therefore'这个字符串的行,-n 表示结果显示对应的行号。

[root@xiaoz93 ~]# grep -n 'therefore' 1.txt 
2:Yes, instances in a stopped state continue to reserve dedicated system resources (RAM, SSD storage, IP aliases, CPU) and therefore incur charges until you destroy the instance. 

使用-i来忽略大小写,找出含有'do'字符的行,如下:

[root@xiaoz93 ~]# grep -n -i 'do' 1.txt 
1:Do you charge for stopped instances?

使用-v进行反转查找,找出不含'do'字符的行,如下:

[root@xiaoz93 ~]# grep -n -i -v 'do' 1.txt 
2:Yes, instances in a stopped state continue to reserve dedicated system resources (RAM, SSD storage, IP aliases, CPU) and therefore incur charges until you destroy the instance. 
3:If you wish to no longer accumulate charges for a virtual machine, please use the DESTROY button in the customer portal.

一些注意事项

『正规表示法的特殊字节』与一般在命令列输入命令的『万用字节』并不相同, 例如,在万用字节当中的 * 代表的是『 0 ~ 无限多个字节』的意思,但是在正规表示法当中, * 则是『重复 0 到无穷多个的前一个 RE 字符』的意思~使用的意义并不相同,不要搞混了!

参考

此文参考了如下内容,如果需要获取更多详细说明可以看看。

标签: grep命令

发表评论: