Sed命令


Sed的常用命令语法
Sed
是一个非交互性文本流编辑器。它编辑文件或标准输入导出的文本拷贝。
1
.行的匹配
[root@mypc /]# sed -n '2p' /etc/passwd
打印出第2
[root@mypc /]# sed -n '1,3p' /etc/passwd
打印出第1到第3
[root@mypc /]# sed -n '$p' /etc/passwd
打印出最后一行
[root@mypc /]# sed -n '/user/'p /etc/passwd
打印出含有user的行
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
[root@mypc /]# sed -n '/\$/'p /etc/passwd
打印出含有$元字符的行,$意为最后一行
2
.插入文本和附加文本(插入新行)
[root@mypc /]# sed -n '/FTP/p' /etc/passwd
打印出有FTP的行
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
[root@mypc /]# sed '/FTP/ a\ 456' /etc/passwd
在含有FTP的行后面新插入一行,内容为456
[root@mypc /]# sed '/FTP/ i\ 123' /etc/passwd
在含有FTP的行前面新插入一行,内容为123
[root@mypc /]# sed '/FTP/ i\ "123"' /etc/passwd
在含有FTP的行前面新插入一行,内容为"123"
[root@mypc /]# sed '5 a\ 123' /etc/passwd
在第5行后插入一新行,内容为123
[root@mypc /]# sed '5 i\ “12345”' /etc/passwd
在第5行前插入一新行,内容为“12345”
3
.删除文本
[root@mypc /]# sed '1d' /etc/passwd
删除第1
[root@mypc /]# sed '1,3d' /etc/passwd
删除第13
[root@mypc /]# sed '/user/d' /etc/passwd
删除带有user的行
4
替换文本,替换命令用替换模式替换指定模式,格式为:
[ a d d r e s s [
address]] s/ pattern-to-find /replacement-pattern/[g p w n]
[root@mypc /]# sed 's/user/USER/' /etc/passwd
将第1user替换成USER,g表明全局替换
[root@mypc /]# sed 's/user/USER/g' /etc/passwd
将所有user替换成USER
[root@mypc /]# sed 's/user/#user/' /etc/passwd
将第1user替换成#user,如用于屏蔽作用
[root@mypc /]# sed 's/user//' /etc/passwd
将第1user替换成空
[root@mypc /]# sed 's/user/&11111111111111/' /etc/passwd
如果要附加或修改一个很长的字符串,可以使用(&)命令,&命令保存发现模式以便重新调用它,然后把它放在替换字符串里面,这里是把&放前面
[root@mypc /]# sed 's/user/11111111111111&/' /etc/passwd
这里是将&放后面
5.
快速一行命令
下面是一些一行命令集。([]表示空格,[]表示ta b键)
‘s / \ . $ / / g’
删除以句点结尾行
‘-e /abcd/d’
删除包含a b c d的行
‘s / [ ] [ ] [ ] * / [ ] / g’
删除一个以上空格,用一个空格代替
‘s / ^ [ ] [ ] * / / g’
删除行首空格
‘s / \ . [ ] [ ] * / [ ] / g’
删除句点后跟两个或更多空格,代之以一个空格
‘/ ^ $ / d’
删除空行
‘s / ^ . / / g’
删除第一个字符
‘s /COL \ ( . . . \ ) / / g’
删除紧跟C O L的后三个字母
‘s / ^ \ / / / g’
从路径中删除第一个\
‘s / [ ] / [ ] / / g’
删除所有空格并用t a b键替代
‘S / ^ [ ] / / g’
删除行首所有t a b
‘s / [ ] * / / g’
删除所有t a b
如果使用se d对文件进行过滤,最好将问题分成几步,分步执行,且边执行边测试结果。
经验告诉我们,这是执行一个复杂任务的最有效方式。