前言
sed 全名為 stream editor,是用于文本處理的流編輯器,支持正則運算式, sed處理文本時是一次處理一行內容
關注公眾號,一起交流,微信搜一搜: 潛行前行
sed語法
- 示例:
sed -i 's/原字串/新字串/' /home/test.txt - sed命令處理的內容是模式空間中的內容,而非直接處理檔案內容,如果加上引數 i 則是直接修改檔案內容
sed [-nefr引數] [動作] [檔案]
| 選項與引數 | 描述 |
|---|---|
| -n | 使用 silent 模式,在一般 sed 的用法中,輸入的資料都會被輸出到螢屏上,但如果加上 -n 引數后,則不會顯示,如果有跟著 p 標志,被 sed 特殊處理的那一行會被列出來 |
| -e | 直接在命令列界面上進行 sed 的動作編輯,執行多條子命令 |
| -f | 將 sed 的動作寫在一個檔案內, -f filename 執行腳本檔案的 sed 動作 |
| -r | sed 的動作支持的是延伸型正則運算式的語法 |
| -i | 直接修改讀取的檔案內容 |
- 選項-n,加上-n選項后被設定為安靜模式,也就是不會輸出默認列印資訊,除非子命令中特別指定列印 p 選項,則只會把匹配修改的行進行列印
---- 兩行都列印出來 ----
server11:~/test # echo -e 'hello \n world' | sed 's/hello/csc/'
csc
world
---- 一行也沒列印 -----
server11:~/test # echo -e 'hello \n world' | sed -n 's/hello/csc/'
---- 列印了匹配行 -----
server11:~/test # echo -e 'hello \n world' | sed -n 's/hello/csc/p'
csc
- 選項-e,多條子命令連續進行操作
echo -e 'hello world' | sed -e 's/hello/csc/' -e 's/world/lwl/'
結果:csc lwl
- 選項-i,直接修改讀取的檔案內容
server11:~/test # cat file.txt
hello world
server11:~/test # sed 's/hello/lwl/' file.txt
lwl world
server11:~/test # cat file.txt
hello world
---- 加上引數 i 可以直接修改檔案內容----
server11:~/test # sed -i 's/hello/lwl/' file.txt
lwl world
server11:~/test # cat file.txt
hello world
- 選項-f,執行檔案腳本
sed.script腳本內容:
s/hello/A/
s/world/B/
------
echo "hello world" | sed -f sed.script
結果:A B
- 選項-r,支持正則運算式
echo "hello world" | sed -r 's/(hello)|(world)/csc/g'
csc csc
動作: [n1[,n2]] function
n1, n2 :可選項,一般代表“選擇進行動作的行數”,舉例來說,如果動作是需要在 10 到 20 行之間進行的,則表示為 10,20 [function]
test.txt 內容
111
222
333
444
----- 洗掉非第2第3行之間的所有行 ----------
server11:~ # sed -i '2,3!d' test.txt
server11:~ # cat test.txt
222
333
function 有以下這些選項
| function | 描述 |
|---|---|
| a | 新增:a 的后面可以接字串,而這些字串會在新的一行出現(目前的下一行) |
| i | 插入:i 的后面可以接字串,而這些字串會在新的一行出現(目前的上一行) |
| c | 取代:c 的后面可以接字串,這些字串可以取代 n1,n2 之間的行 |
| d | 洗掉:因為是洗掉啊,所以 d 后面通常不接任何東西 |
| p | 列印:亦即將某個選擇的資料印出,通常 p 會與引數 sed -n 一起運行 |
| s | 取代:可以直接進行取代的作業哩!通常這個 s 的動作可以搭配正則運算式! 例如:1,20 s/old/new/g |
- function:-a,行后插入新行
sed -i '/特定字串/a 新行字串' fileName
- function:-i,行前插入新行
sed -i '/特定字串/i 新行字串' fileName
- function:-c,修改指定內容行
sed -i '/特定字串/c csc lwl' fileName
- function:-d,洗掉特定字串
sed -i '/特定字串/d' fileName
sed s子命令: s/{pattern}/{replacement}/{flags}
-
如果{pattern}包含正則運算式,則需要加上 -r
-
如果{pattern}存在分組,{replacement}中的"\n"代表第n個分組,"&"代表整個匹配的字串,詳情看示例
-
flags的引數如下
| flags | 描述 |
|---|---|
| n | 可以是1-512,表示第n次出現的情況進行替換 |
| g | 全域更改 |
| p | 列印模式空間的內容 |
| w file | 寫入到一個檔案file中 |
- 示例
server11:~ # echo -e 'hello 1112 world' | sed -r 's/([a-z]+)( [0-9]+ )([a-z]+)/&/'
hello 1112 world
server11:~ # echo -e 'hello 1112 world' | sed -r 's/([a-z]+)( [0-9]+ )([a-z]+)/\3\2\1/'
world 1112 hello
參考文章
- sed -i命令詳解及入門攻略
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/287256.html
標籤:其他
