Linux中awk工具的使用详解( 六 )


在正则表达式中^表示以某某字符或者字符串开头 。
使用正则表达式来匹配所有以 "true" 字符串结尾的行
$ awk '/true$/{print $0}' poetry.txtThis above all: to thine self be true
在正则表达式中$表示以某某字符或者字符串结尾 。
又一个正则表达式例子如下
$ awk '/m[a]t/{print $0}' poetry.txtNo matter how dark long, may eventually in the day arrival
上面这个正则表达式/m[a]t/表示匹配包含字符 m,然后接着后面还要包含中间方括号中表示的单个字符 a,最后还要包含字符 t 的行,输出结果中只有单词 "" 符合这个正则表达式的匹配 。因为正则表达式[a]方括号中表示匹配里面的任意单个字符 。
继续上面的一个新例子如下
$ awk '/^Th[ie]/{print $0}' poetry.txtThis above all: to thine self be trueThere is nothing either good or bad, but thinking makes it soThere’s a special providence in the fall of a sparrow
这个例子中的正则表达式/^Th[ie]/表示匹配以字符串 "Thi" 或者 "The" 开头的行,正则表达式方括号中表示匹配其中的任意单个字符 。
再继续上面的新的用法
$ awk '/s[a-z]/{print $0}' poetry.txtThis above all: to thine self be trueThere is nothing either good or bad, but thinking makes it soThere’s a special providence in the fall of a sparrow
正则表达式/s[a-z]/表示匹配包含字符 s 然后后面跟着任意 a 到 z 之间的单个字符的字符串,比如 "se", "so", "sp" 等等 。
正则表达式[]方括号中还有一些其他用法比如下面这些
[a-zA-Z]表示匹配小写的 a 到 z 之间的单个字符,或者大写的 A 到 Z 之间的单个字符[^a-z]符号 `^` 在方括号里面表示取反,也就是非的意思,表示匹配任何非 a 到 z 之间的单个字符
正则表达式中的星号*和加号+的使用方法
$ awk '/go*d/{print $0}' poetry.txtThere is nothing either good or bad, but thinking makes it so
上面这个表示匹配包含字符串 "god",并且中间的字母 "o" 可以出现 0 次或者多次,比如单词 "good" 就符合这个要求 。正则表达式中的+和星号原理差不多,只是加号表示任意 1 个或者 1 个以上,也就是必须至少要出现一次 。
正则表达式问号 ? 的使用方法
$ awk '/ba?d/{print $0}' poetry.txtThere is nothing either good or bad, but thinking makes it so