歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 使用sed對文件進行操作

使用sed對文件進行操作

日期:2017/2/28 14:55:38   编辑:Linux教程
一.附加文本
使用a\在指定行後面附加1行或多行;若不指定放置的位置,則默認放到每一行的後面。
附加文本時,不允許指定范圍,只允許一個地址模式。
附加格式:
[address] a\
text\
text\
...
text
注意:
1.a\通知sed對a\後面的內容進行附加操作。
2.每行後面都有"\",當sed執行到\時,將創建一個新行,並將內容添加進去。
3.最後一行不能有"\"。
例子:
如果將附加的第一行最後的"\"去掉,那麼運行腳本將會報錯。
pg append.sed
#!bin/sed -f

# append text
/company/ a\
Then suddenly it happened.
_yeeXun.
執行之後:
sed -f append.sed quote.txt
sed: Unrecognized command: _yeeXun.

修改之後
pg append.sed
#!bin/sed -f

# append text
/company/ a\
Then suddenly it happened.\
_yeeXun.
執行腳本:
sed -f append.sed quote.txt
The honeysuckle band played all night long for noly $90.
It was an evening of splendid music and company.
Then suddenly it happened.
_yeeXun.
Too bad the disco floor fell through at 23:10.
The local nurse Miss P.Neave was in attendance.

因為sed不與原文件打交道,編輯的只是其一個拷貝,所以我們附加的數據不會寫到文件中;
當執行上面的命令之後,我們查看下quote.txt文件:
pg quote.txt
The honeysuckle band played all night long for noly $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:10.
The local nurse Miss P.Neave was in attendance.


二.修改文本
使用c\修改指定行,格式:
[address[,address]] c\
text\
text\
...
text
address:行位置,可以使用正則表達式定位,也可以直接指定行號。
text:為替換的文本,注意最後一行沒有"\"。
例子
替換第三行數據:
pg change.sed
# change date
/bad/ c\
[Two good.]\
next goods.
運行腳本:
sed -f change.sed quote.txt
The honeysuckle band played all night long for noly $90.
It was an evening of splendid music and company.
[Two good.]
next goods.
The local nurse Miss P.Neave was in attendance.
Copyright © Linux教程網 All Rights Reserved