把sed当作命令解释器使用

[root@sishen ~]# vim script.sed

#!/bin/sed -f

#交换第一列和第二列

s/([^,]*),([^,]*),(.*).*/2,1, 3/g

#把整行内容放入<>中

s/^.*/<&>/

#把Developer替换为IT Manager

s/Developer/IT Manager/

#把Manager替换为DIrectory

s/Manager/Directory/

添加可执行权限

[root@sishen ~]# chmod u+x script.sed

[root@sishen ~]# ./script.sed employee.txt

<John Doe,101, CEO>

<Jason Smith,102, IT Directory>

<Raj Reddy,103, Sysadmin>

<Anand Ram,104, IT Directory>

<Jane Miller,105, Sales Directory>

<Jane Miller,#106, Sales Directory>

<Jane Miller,#107, Sales Directory>

使用-n屏蔽默认输出

[root@sishen ~]# vim sc.sed

#!/bin/sed -nf

/root/ p

/nobody/ p

/mail/ p

[root@sishen ~]# chmod +x sc.sed

[root@sishen ~]# ./sc.sed /etc/passwd

root:x:0:0:root:/root:/bin/bash

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

nobody:x:99:99:Nobody:/:/sbin/nologin

nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin

下面来测试下是否加-n,结果会如何

[root@sishen ~]# ./sc.sed /etc/passwd

root:x:0:0:root:/root:/bin/bash

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

………………

[root@sishen ~]# vim sc.sed

#!/bin/sed -fn

/root/ p

/nobody/ p

/mail/ p

[root@sishen ~]# ./sc.sed /etc/passwd

/bin/sed: couldn't open file n: No such file or directory

-nf一定不能写反

注意:无论参数有多少个,参数顺序如何,参数f后面必须接文件名

直接修改输入文件

前面提到sed默认不会修改输入文件,它只会把输出打印到标准输出上,当想保存结果时,把输出重定向到文件(或使用w命令)

[root@sishen ~]# cp employee.txt employee1.txt #先备份一下

[root@sishen ~]# sed 's/John/Johnny/' employee.txt > new-employee.txt

[root@sishen ~]# mv new-employee.txt employee.txt

mv: overwrite `employee.txt'? y

使用-i选项可以直接修改输入文件

[root@sishen ~]# sed -i 's/John/Johnny/' employee.txt

[root@sishen ~]# cat employee.txt

101,Johnnyny Doe,CEO

102,Jason Smith,IT Manager

103,Raj Reddy,Sysadmin

104,Anand Ram,Developer

105,Jane Miller,Sales Manager

#106,Jane Miller,Sales Manager

#107,Jane Miller,Sales Manager

再次提醒:-i会修改输入文件。或许这正是你想要的,但是务必小心。一个保护性的措施是在-i后面加上备份拓展,这一sed就会在修改原始文件之前备份一份

[root@sishen ~]# sed -ibak 's/John/Johnny/' employee.txt

[root@sishen ~]# ls | grep ^em

employee.txt

employee.txtbak

注意:-i后面可以接任意一个字符串或数字并非一定要是bak

还有另外一种写法效果一样

原文地址:https://www.cnblogs.com/zd520pyx1314/p/6061347.html