正则表达式笔记

来源:互联网 发布:淘宝小二介入要多久 编辑:程序博客网 时间:2024/04/29 18:02
不同的语系编码的顺序不一样
LANG=C : 0 1 2 3 ... A B C D ... Z a b c d ... z
LANG=zh_CN: 0 1 2 3 4 ... a A b B c C ... z Z
使用正则表达式时,需要留意环境的语系是什么,否则会有不同的结果
*[:alnum:] 英文大小写字符及数字 0-9 A-Z a-z
*[:alpha:]  英文大小写 A-Z a-z
[:blank:]
[:cntrl:]
*[:digit:]  数字 0-9
[:graph:]
[:graph:]
*[:lower:] 小写字母 a-z
[:print:]
[:punct:]
*[:upper:] 大写字母 A-Z
[:space:]
[:xdigit:]

grep的一些参数
grep [-A] [-B] [--color=auto] '搜索字符' filename
-A 后加数字,为after意思
-B 后加数字,为before意思

用dmesg列出内核信息,在以grep找出含eth的那行
dmesg | grep 'eth'

承上,找到关键字显色,且加上行号
dmesg | grep -n --color=auto 'eth'

承上,在关键字所在行的前两行和后三行也一起找出来显示
dmesg | grep -n -A2 -B3 --color=auto 'eth'

grep主要功能是进行字符串数据的对比,然后将符号用户需求的字符串打印出来,在数据中查找一条字符串时,是以整行为单位来进行数据选取的

1.查找特定字符串
查找特定字符串 the grep -n 'the' test.txt
反向选择,除了the的才显示 grep -vn 'the' test.txt
大小写都显示 grep -in 'the' test.txt

2.利用中括号[]来查找集合字符
查找test或taste两个单词 grep -n 't[ae]st' test.txt
查找有oo的字符 grep -n 'oo' test.txt
不想oo前面有g grep -n '[^g]oo' test.txt
不想oo前面有小写字符 grep -n '[^a-z]oo' test.txt
取得有数字的那一行 grep -n '[0-9]' test.txt
其他表示法 grep -n '[^[:lower:]]oo' test.txt
grep -n '[[:digit:]]' test.txt

3.行首和行尾字符 ^ $
the只在行首出现 grep -n '^the' test.txt
开头是小写字母 grep -n '^[a-z]' test.txtgrep -n '^[[:lower:]]' test.txt
开头不是英文字母 grep -n '^[^a-zA-Z]' test.txt
行尾结束为小数点 . grep -n '\.$' test.txt小数点会有其他意义,用转义字符加以解除
找出空白行 grep -n '^$' test.txt开头就是结尾
linux中找注释的语句 grep -n '^[#]' test.txtgrep -vn '^[^#]' test.txt

4.任意一个字符.和重复字符*
.(小数点) :代表一定有一个任意字符的意思
*(星号) : 代表重复前一个0到无穷多次的意思,为组合状态
开头是g 结束是d,中间两个字符 grep -n 'g..d' test.txt
.* 代表零个或多个任意字符 grep -n 'g.*d' test.txt


5.限定连续RE字符范围{ }
找到两个o的字符串 grep -n 'o\{2\}' test.txt{ }需要转义
g后面接2到5个o,在接一个g grep -n 'go\{2,5\}g' test.txt
两个以上的o grep -n 'go\{2,\}g' test.txt

找出文件类型是连接文件属性的文件名 ls -l /etc | grep '^l'

sed工具
参数:
-n 安静模式,只有经过sed特殊处理的那一行才会显示出来

a 新增 后接字符串,在新的一行出现(后一行)
c 替换 后接字符串,替换n1,n2之间的行
d 删除 
i  插入 后接字符串,在新的一行出现(前一行)
p 打印
s  替换

将文件内容显示出来并且打印行号,同时将2~5行删除
nl /etc/passwd | sed '2,5d'
删除2~最后一行
nl /etc/passwd | sed '2,$d'
在第二行后加上字符
nl /etc/passwd | sed '2a drink tea'
在第二行前面加上字符 以反斜杠\可以增加新的行
nl /etc/passwd | sed '2i drink tea or .....\
how are you'
多行替换
nl /etc/passwd | sed '2,6c no 2-6 hello world'
只列出指定的几行
nl /etc/passwd | sed -n '3,9p'
查找并替换
sed 's/要被替换的字符/新的字符/g'
例子1:
ifconfig eth0 | grep 'inet addr' :
inet addr:192.168.101.2  Bcast:192.168.101.255  Mask:255.255.255.0
ifconfig eth0 | grep 'inet addr' | sed 's/.*addr://g' :
192.168.101.2  Bcast:192.168.101.255  Mask:255.255.255.0
ifconfig eth0 | grep 'inet addr' | sed 's/.*addr://g' | sed 's/Bcast.*$//g' :
192.168.101.2

例子2:
将man所在行列出 cat /etc/man.config | grep 'MAN'
删掉批注之后的数据 cat /etc/man.config | grep 'MAN' | sed 's/#.*$//g'
删掉空白行 cat /etc/man.config | grep 'MAN' | sed 's/#.*$//g' | sed '/^$/d'

直接修改文件内容
将每一行结尾的 . 换为 !
sed -i 's/\.$/\!/g' test.txt 参数-i为直接修改后面的文件而不在屏幕输出
在最后一行加入文字 '# hello world'
sed -i '$a # hello world' test.txt

扩展正则表达式
egrep
+ 重复一个或一个以上的前一个RE字符
? 零个或一个的前一个RE字符
| 用或(or)的方式找出数个字符串
() 找出组字符串
()+ 多个重复组的判别
0 0
原创粉丝点击