shell sed 字符串替換


content

macname@localhost Desktop % 
macname@localhost Desktop % cat ddd
This is a test of the test script.
This is the second test of the test script.
macname@localhost Desktop %

 

#在行中替換文本

macname@localhost Desktop % sed 's/test/trial/' ddd
This is a trial of the test script.
This is the second trial of the test script.
macname@localhost Desktop %

 

#指定sed編輯器用新文本替換第幾處模式匹配的地方

macname@localhost Desktop % 
macname@localhost Desktop % sed 's/test/trial/2' ddd
This is a test of the trial script.
This is the second test of the trial script.
macname@localhost Desktop %

 

 

將替換標記指定為2的結果就是:sed編輯器只替換每行中第二次出現的匹配模式。
g替換標 記使你能替換文本中匹配模式所匹配的每處地方

macname@localhost Desktop % 
macname@localhost Desktop % sed 's/test/trial/g' ddd
This is a trial of the trial script.
This is the second trial of the trial script.
macname@localhost Desktop %

 


p替換標記會打印與替換命令中指定的模式匹配的行。這通常會和sed的-n選項一起使用。
-n選項將禁止sed編輯器輸出。但p替換標記會輸出修改過的行。將二者配合使用的效果就是 只輸出被替換命令修改過的行

macname@localhost Desktop % cat ddd
This is a test of the test script.
This is the second test of the test script.
Dededede
Hahahahhahahaah
macname@localhost Desktop % 
macname@localhost Desktop % sed -n 's/test/trial/p' ddd
This is a trial of the test script.
This is the second trial of the test script.
macname@localhost Desktop %

 


w替換標記會產生同樣的輸出,不過會將輸出保存到指定文件中

macname@localhost Desktop % cat ddd
This is a test of the test script.
This is the second test of the test script.
Dededede
Hahahahhahahaah
macname@localhost Desktop % sed 's/test/trial/w test.txt' ddd
This is a trial of the test script.
This is the second trial of the test script.
Dededede
Hahahahhahahaah
macname@localhost Desktop % cat test.txt
This is a trial of the test script.
This is the second trial of the test script.
macname@localhost Desktop %

 


sed編輯器允許選擇其他字符來作為替換命令中的字符串分隔符,這里感嘆號被用作字符串分隔符

macname@localhost Desktop % cat ddd
This is a test of the test script.
This is the second test of the test script.
Dededede
Hahahahhahahaah
macname@localhost Desktop % 
macname@localhost Desktop % sed -n 's!test!trial!p' ddd
This is a trial of the test script.
This is the second trial of the test script.
macname@localhost Desktop %

 

在這個例子中,感嘆號被用作字符串分隔符,這樣路徑名就更容易閱讀和理解了。

macname@localhost Desktop % 
macname@localhost Desktop % sed 's!/bin/bash!/bin/csh!' /etc/passwd

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM