首页 > 代码库 > sed学习

sed学习

cat netstat.txt

Proto Recv-Q Send-Q Local-Address          Foreign-Address             State
tcp        0      0 0.0.0.0:3306           0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:80             0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:9000         0.0.0.0:*                   LISTEN
  tcp        0      0 coolshell.cn:80        124.205.5.146:18245         TIME_WAIT
  tcp        0      0 coolshell.cn:80        61.140.101.185:37538        FIN_WAIT2
tcp        0      0 coolshell.cn:80        110.194.134.189:1032        ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49809       ESTABLISHED
  tcp        0      0 coolshell.cn:80        116.234.127.77:11502        FIN_WAIT2
tcp        0      0 coolshell.cn:80        123.169.124.111:49829       ESTABLISHED
  tcp        0      0 coolshell.cn:80        183.60.215.36:36970         TIME_WAIT
tcp        0   4166 coolshell.cn:80        61.148.242.38:30901         ESTABLISHED
  tcp        0      1 coolshell.cn:80        124.152.181.209:26825       FIN_WAIT1
tcp        0      0 coolshell.cn:80        110.194.134.189:4796        ESTABLISHED
  tcp        0      0 coolshell.cn:80        183.60.212.163:51082        TIME_WAIT
tcp        0      1 coolshell.cn:80        208.115.113.92:50601        LAST_ACK
tcp        0      0 coolshell.cn:80        123.169.124.111:49840       ESTABLISHED
  tcp        0      0 coolshell.cn:80        117.136.20.85:50025         FIN_WAIT2
tcp        0      0 :::22                  :::*                        LISTEN

普通匹配:

#&变量为匹配文字
sed ‘s/my/[&]/g‘ my.txt
#合并两行为一行
sed ‘N;s/\n/,/‘ pets.txt
#打印从/dog/到/fish/之间的行
sed -n ‘/dog/,/fish/p‘ my.txt
#匹配dog行和其后面连续3行
sed ‘/dog/,+3s/^/# /g‘ pets.txt

多模式替换

#一次替换多个模式
sed  ‘/TIME/d;s/^ *//g‘ netstat.txt
#或者指定1到4行
sed  ‘1,4 {/TIME/d;s/^ *//g}‘ netstat.txt

多条件匹配

对第3到6行,先匹配WAIT,从匹配项里删除匹配到FIN的行
sed "/WAIT/{/FIN/d}" netstat.txt

本文出自 “fightering-cluter” 博客,请务必保留此出处http://3974020.blog.51cto.com/3964020/1550294

sed学习