2024年4月27日发(作者:)
grep用法详解:grep与正则表达式
首先要记住的是: 正则表达式与通配符不一样,它们表示的含义并不相
同!
正则表达式只是一种表示法,只要工具支持这种表示法,那么该工具就
可以处理正则表达式的字符串。vi grep ,awk ,sed 等都支持正则表达
式.
1基础正则表达式
grep 工具,以前介绍过。
grep -[acinv] '搜索内容串' filename
-a 以文本文件方式搜索
-c 计算找到的符合行的次数
-i 忽略大小写
-n 顺便输出行号
-v 反向选择,即找 没有搜索字符串的行
其中搜索串可以是正则表达式!
1
搜索有the的行,并输出行号
$grep -n 'the' regular_
搜索没有the的行,并输出行号
$grep -nv 'the' regular_
2 利用[]搜索集合字符
[] 表示其中的某一个字符 ,例如[ade] 表示a或d或e
woody@xiaoc:~/tmp$ grep -n 't[ae]st' regular_
8:I can't finish the test.
9:Oh! the soup taste good!
可以用^符号做[]内的前缀,表示除[]内的字符之外的字符。
比如搜索oo前没有g的字符串所在的行. 使用 '[^g]oo' 作搜索字符
串
woody@xiaoc:~/tmp$ grep -n '[^g]oo' regular_
2:apple is my favorite food.
3:Football game is not use feet only.
18:google is the best tools for search keyword.
19:goooooogle yes!
[] 内可以用范围表示,比如[a-z] 表示小写字母,[0-9] 表示0~9的数
字, [A-Z] 则是大写字母们。[a-zA-Z0-9]表示所有数字与英文字符。 当
然也可以配合^来排除字符。
搜索包含数字的行
woody@xiaoc:~/tmp$ grep -n '[0-9]' regular_
5:However ,this dress is about $ 3183 dollars.


发布评论