sed 替换命令(2)

输入文件不会被修改,sed 只在模式空间中执行替换命令,然后输出模式空间的
内容。
文本文件 employee.txt

101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager

1.用 Director 替换所有行中的 Manager
替换命令用到参数s 注意代码格式

[root@localhost /]# sed 's/Manager/Director/' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Director
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Director

2.只把包含 Sales 的行中的 Manager 替换为 Director

[root@localhost /]# sed '/Sales/s/Manager/Director/' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Director

3.全局标志 g
用大写 A 替换第一次出现的小写字母 a

[root@localhost /]# sed 's/a/A/' employee.txt
101,John Doe,CEO
102,JAson Smith,IT Manager
103,RAj Reddy,Sysadmin
104,AnAnd Ram,Developer
105,JAne Miller,Sales Manager

把所有小写字母 a 替换为大写字母 A

 [root@localhost /]# sed 's/a/A/g' employee.txt
101,John Doe,CEO
102,JAson Smith,IT MAnAger
103,RAj Reddy,SysAdmin
104,AnAnd RAm,Developer
105,JAne Miller,SAles MAnAger

4.数字标志
把第二次出现的小写字母 a 替换为大写字母 A

[root@localhost /]# sed 's/a/A/2' employee.txt
101,John Doe,CEO
102,Jason Smith,IT MAnager
103,Raj Reddy,SysAdmin
104,Anand RAm,Developer
105,Jane Miller,SAles Manager

建立一下文件

vi substitute-locate.txt
locate command is used to locate files
locate command uses database to locate files
locate command can also use regex for searching

用刚才建立的文件,把每行中第二次出现的 locate 替换为 find

[root@localhost /]# sed 's/locate/find/2' substitute-locate.txt
locate command is used to find files
locate command uses database to find files
locate command can also use regex for searching

5.打印标志 p
把每行中第二次出现的 locate 替换为 find 并打印出来

在这里插入代码片

猜你喜欢

转载自blog.csdn.net/weixin_43150761/article/details/83152456
今日推荐