sed 替換命令(2)
阿新 • • 發佈:2018-11-09
輸入檔案不會被修改,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 注意程式碼格式
[[email protected] /]# 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
[[email protected] /]# 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
[[email protected] /]# 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
[[email protected] /]# 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
[[email protected] /]# 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
[[email protected] /]# 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 並打印出來
在這裡插入程式碼片