在指定行前面添加数据。
[address] i\
text\
text\
...
text
address:行位置,可以使用正则表达式定位,也可以直接指定行号。
text:为替换的文本,注意最后一行没有"\"。
例如:
pg insert.sed
# insert data
/.*ing/ i\
[the insert date].
运行脚本:
sed -f insert.sed quote.txt
The honeysuckle band played all night long for noly $90.
[the insert date].
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.
四.删除文本
删除文件中的内容,删除1行或者连续的多行,或者匹配某个模式的所有行格式:
[address[,address]] d
文件信息:
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.
删除第一行:
sed '1d' quote.txt
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.
删除第一到第三行:
sed '1,3d' quote.txt
The local nurse Miss P.Neave was in attendance.
删除最后一行:
sed '$d' 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.
使用正则表达式删除符合条件的所有行。
删除包含以字母a开头,以字母d结尾,总长为3的行,符合的有第一行(band),第二行(and)。
sed '/a.d/d' quote.txt
Too bad the disco floor fell through at 23:10.
The local nurse Miss P.Neave was in attendance.
五.替换文本,格式:
[address[,address]] s/pattern-to-find/replacement-pattern/[g p w n]
address:可选项
g:默认情况下,只替换首次出现模式,使用g替换全部所有出现的模式;
p:默认sed将所有被替换行写入标准输出,加p将使-n选项无效;-n不打印输出结果。
w:文件名,使用此选项将输出定向到一个文件。
将小写的floor替换为大写的FLOOR:
sed 's/floor/FLOOR/' 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.
将包含"$"符号的行$符号删除掉:
包含$符号的行:
sed -n '/$.*/p' quote.txt
The honeysuckle band played all night long for noly $90.
删除$(使用空替代)符号后的行:
sed -n 's/\$//p' quote.txt
The honeysuckle band played all night long for noly 90.
将首次出现的"The"单词替换为"THE",并输出到另一个文件中
若sed.out存在则向里面写数据,所不存在则创建此文件并写数据:
sed 's/The/THE/w sed.out' 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.
查看文件sed.out:
pg sed.out
THE honeysuckle band played all night long for noly $90.
THE local nurse Miss P.Neave was in attendance.
