sed是一個文本流處理器,配合正則表達式用可以實現很多文本處理操作。
和grep一樣,sed是一行一行的處理的。sed處理文本時,首先會將源文件復制一份到內存中,然后將文本一行一行拿到模式空間內進行操作,最后輸出到標準輸出,即屏幕上。
在模式空間中,每一行都會根據用戶給的條件進行匹配,匹配到了進行編輯后輸出,沒有匹配到,直接輸出到標準輸出。sed除了模式空間還有一個保持空間,能夠讓行在模式空間和保持空間多次進行處理,進而完成復雜的處理工作。
sed [option]...'script' [input-file]...
script:
地址定界、編輯命令
常用選項:
-n, --quiet, --slient:不輸出模式空間中的內容到屏幕,也就是默認
suppress automatic printing of pattern space:自動不輸出模式空間中的內容
-e script, --expression=script:添加可執行的腳本,用腳本來處理文本,多點編輯
add the script to the commands to be executed.
-f script, --expression=script:
add the contents of script-file to the commands to be executed
-r. --regxp-extended:支持使用擴展正則表達式
-i[SUFFIX], --in-place[=SUFFIX]:直接編輯源文件
地址定界:
1.空地址:全文處理
2.單地址:
# :第#行
/patter/ :被此模式匹配到的每一行
3.地址范圍:
#,# :
#,+# :從第#行開始的第#行
#,/pat1/ :從第#行開始,到第一次匹配到模式的行
/pat1/,/pat2/ :從/pat1/到/pat2/
4.步進:~
1~2:所有奇數行
編輯信息(COMMANDS):
除了用d模式,都用上-n選項
d :將匹配到的行刪除;
p :print the current pattern space
輸出當前模式空間中的內容
a \text:
append text, which has each embedded newline preceded by a backslash
追加新行,反斜線前的范圍內每一行后都追加新的一行。可以用\n實現多行追加
i \text:
insert text,which has each embedded newline preceded by a backslash
插入新行,反斜線前指范圍內每一行前插入新的一行??梢杂肻n實現多行追加
c \text:
replace the selected lines with text,which has each embedded newline preceded by a backlash.
將指定的行更換文本,~。~
w /path/to/somefile:
write the current pattern space to filename
保存模式空間匹配到的行至指定的文件中;
r /path/to/somefile:
append text read from filename
文件合并
= :為模式匹配到的行打印行號
! :條件取反,在COMMAND前用;
地址定界!編輯命令
s/// :查找替換,其分隔符可自行指定,常用 s@@@,s###等
替換標記:
g :全局替換
W /path/to/somefile:將替換成功的結果保存至指定文件中;
P :顯示替換成功的行
在hold space(保持空間)中還有一些高級命令:
高級編輯命令:
h H copy/append pattern space to hold space.
g G Copy/append hold space to pattern space.
x Exchange the contents of the hold and pattern spaces.
n N Read/append the next line of input into the pattern space.
d Delete pattern space. Start next cycle.
D If pattern space contains no newline, start a normal new cycle as if the d command was issued.
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/90827
博文內容上簡單了點,sed還是有蠻多知識可以總結的~可以擴充一下,繼續加油哈~