Intro
BRE basic regulat expression, used by 'grep', 'sed', 'vi'
ERE extended regular expression, used by 'egrep, awk'
PRE perl regx
About Grep
grep 默认BRE
grep -E 开启ERE
grep -F 固定字串匹配
Examples of BRE
建议打开 alias grep='grep --color=auto',显示匹配的部分
匹配任意字符
regex='.*'
'.'符号不匹配换行符
$echo -ne '\n' | grep -qs '.' ; echo $? #返回1
'$'匹配换行符
$echo -ne '\n' | grep -qs '$' ; echo $? #返回0
锚位:空行
regex='^$'
匹配英文字符
$grep '[a-zA-Z]' textfile
不匹配英文字母
$grep '[^a-zA-Z]' textfile
匹配元字符
$grep '[].\*[()-]' textfile #注意'-'的顺序
叠词xx:反向引用
$grep '\(.\)\1' text.txt
叠词xyyx:反向引用
$grep '\(.\)\(.\)\2\1' text.txt
匹配被引号圈引的字符
$grep "\(['\"]\).*\1" text.txt #注意\"要转义
重复
$echo {{{ | grep '{\{3\}' --color=auto #{}是元字符
分组后重复
$echo comcomcom | grep '\(com\)\{3\}'
或
$echo computer and server | grep -e 'computer' -e 'server'
等价于
$echo computer and server | grep -E 'computer|server'
匹配单词字符
regex = '\w' ='[a-zA-Z0-9_]'
$echo *xs8 | grep '\w\{3\}'
匹配单词结尾或开头(\b和\<的区别暂时不详)
$echo microword |grep 'word\>' #匹配
$echo microwords |grep 'word\>' #不匹配
匹配诸如China, America, Shanghai等大写开头的字串
$grep '\<[A-Z]\w*\>' text.txt
BRE和ERE转换
ERE: a? == BRE: a\{0,1\}
ERE: a+ == BRE: a\{1,\}
ERE: a{m,n} == BRE: a\{m,\n}
ERE: (a) == BRE: \(a\)
ERE: grep -E 'REGEX1|REGEX2'== BRE: grep -e REGEX1 -e REGEX2
阅读(2057) | 评论(0) | 转发(0) |