正则表达式RE
用来处理文本
正则表达式(Regular Expression, RE)是一种字符模式, 用于在查找过程中匹配指定的字符. 在大多数程序里, 正则表达式都被置于两个正斜杠之间;
例如/l[oO]ve/就是由正斜杠界定的正则表达式, 它将匹配被查找的行中任何位置出现的相同模式. 在正则表达式中,元 字符是最重要的概念
元字符使正则表达式具有处理能力。所谓元字符就是指ß那些在正则表达式中具有特殊意义的专用字符,可以用来规定 其前导字符(即位于元字符前面的字符)在目标对象中的出现模式。
正则表达式基本元字符
基本正则表达式元字符 元字符 示例 功能 ^ 行首定位符 ^love(匹配以love开头) $ 行尾定位符 love$(匹配以love结尾) . 匹配单个字符 l..e (匹配以中间为任何字符且l开头e结尾) * 匹配前导符0到多次 全部匹配 grep "o*" /etc/passwd ab*love(匹配ab开头love结尾) .* 匹配任意多个字符 (贪婪匹配 [ ] 匹配方括号中任意一个字符 [lL]ove(匹配love或Love) [ - ] 匹配指定范围内的一个字符 [a-z0-9]ove [^] 匹配不在指定组里的字符 [^a-z0-9]ove \ 用来转义元字符 love\. \< 词首定位符 #由数字或字母组成的 \
正则表达式拓展元字符
= 等于 != 不等于 =~ 匹配 扩展正则表达式元字符 + 匹配一个或多个前导字符 [a-z]+ove ? 匹配零个或一个前导字符 lo?ve "r.*t" 贪婪匹配 -P "r.*?" 非贪婪匹配 a|b 匹配a或b love|hate () 组字符loveable|rs love(able|rs) ov+ ov+ (ov)+ (oo)+ 两个oo出现一次或者多个 (..)(..)\1\2 标签匹配字符 # (love)able\1er x{m} 字符x重复m次 o{5} o{,3} 字符最多出现3次 x{m,} 字符x重复至少m次 o{5,} 字符最少出现5次 x{m,n} 字符x重复m到n次 o{5,10} 字符o重复5到10次
shell 编程-grep
常见参数
egrep 支持正则表达式的拓展元字符 (或grep -E)
grep -v 除它
配合正则练习
例: 编辑文件lianxi.txt内容如下 Two roads diverged in a yellow wood, And sorry I could not travel both And be one traveler, long I stood And looked down one as far as I could To where it bent in the undergrowth; Then took the other, as just as fair, And having perhaps the better claim, Because it was grassy and wanted wear; Though as for that the passing there Had worn them really about the same, And both that morning equally lay In leaves no step had trodden black. Oh, I kept the first for another day! Yet knowing how way leads on to way, I doubted if I should ever come back. I shall be telling this with a sigh Somewhere ages and ages hence: Two roads diverged in a wood,and I— I took the one less traveled by, And that has made all the difference. 1、从文本中查找包含字符串"yellow"的行 grep "yellow" lianxi.txt 2、从文本中查找包含字符串"travel"或"traveler"的行 egrep 'travel|traveler' lianxi.txt 3、从文本中查找以字母"T"开头的行 grep "^T" lianxi.txt 4、从文本中查找以字母";"结尾的行 grep ";$" lianxi.txt 5、从文本中查找包含单词"fair"的行 grep " shell 编程-SED(流文本编辑器) 非交互式编辑器,一次处理一行内容。 sed "参数" '模式' 常用参数 -f 指定一个规则文件 -n 阻止输入行输出 -r 扩展正则 常用模式 s 替换 g 整行(也可以是数字,替换第几个) d 删除 p 打印 a 追加 i 是插入 #sed 's/新值/旧值/' 文件名 使用多重指令时用;隔开: # sed 's/新值/旧值/; s/新值/旧值/' 文件名 使用脚本文件: 脚本:namestate -f
发表评论