sed '1i 添加的內容' file #這是在第一行前添加字符串
sed '$i 添加的內容' file #這是在最后一行行前添加字符串
sed '$a添加的內容' file #這是在最后一行行后添加字符串
sed '1 a\string1\n\string2\n' /etc/passwd #在第1行后插入兩行字符串。
sed '1 i\string1\n\string2\n' /etc/passwd #在第1行前插入兩行字符串
# 注意這里的 " & " 符號,如果沒有 “&”,就會直接將匹配到的字符串替換掉 sed 's/^/添加的頭部&/g' #在所有行首添加 sed 's/$/&添加的尾部/g' #在所有行末添加 sed '2s/原字符串/替換字符串/g' #替換第2行 sed '$s/原字符串/替換字符串/g' #替換最后一行 sed '2,5s/原字符串/替換字符串/g' #替換2到5行 sed '2,$s/原字符串/替換字符串/g' #替換2到最后一行
1
2
3
4
5
|
[root@localhost ~]# cat /tmp/input.txt
null
000011112222
test
|
要求:在1111之前添加AAA,方法如下:
sed -i 's/指定的字符/要插入的字符&/' 文件
1
2
3
4
5
6
|
[root@localhost ~]# sed -i
's/1111/AAA&/'
/tmp/input.txt
[root@localhost ~]# cat /tmp/input.txt
null
0000
AAA
11112222
test
|
要求:在1111之后添加BBB,方法如下:
sed -i 's/指定的字符/&要插入的字符/' 文件
1
2
3
4
5
6
|
[root@localhost ~]# sed -i
's/1111/&BBB/'
/tmp/input.txt
[root@localhost ~]# cat /tmp/input.txt
null
0000
AAA
1111
BBB
2222
test
|
要求:(1) 刪除所有空行;(2) 一行中,如果包含"1111",則在"1111"前面插入"AAA",在"11111"后面插入"BBB"
1
2
3
4
|
[root@localhost ~]# sed
'/^$/d;s/1111/AAA&/;s/1111/&BBB/'
/tmp/input.txt
null
0000
BBB
1111
AAA
2222
test
|
要求:在每行的頭添加字符,比如"HEAD",命令如下:
1
2
3
4
5
6
|
[root@localhost ~]# sed -i
's/^/HEAD&/'
/tmp/input.txt
[root@localhost ~]# cat /tmp/input.txt
HEADnull
HEAD
000011112222
HEAD
HEADtest
|
要求:在每行的尾部添加字符,比如"tail",命令如下:
1
2
3
4
5
6
|
[root@localhost ~]# sed -i
's/$/&tail/'
/tmp/input.txt
[root@localhost ~]# cat /tmp/input.txt
HEADnulltail
HEAD
000011112222
tail
HEADtail
HEADtesttail
|
說明:
1."^"代表行首,"$"代表行尾
2.'s/$/&tail/g'中的
字符s,表示查找替換;
字符&,表示引用前面引用的字段;
字符g代表每行出現的字符全部替換(也叫行內全局替換),如果想在特定字符處添加,g就有用了,否則只會替換每行第一個,而不繼續往后找。
3. 在命令中 /// 和 @@@ 和### 符號等價;
如 sed -i ‘s/1/2/g’ == sed -i 's@1@2@g' == sed -i 's#1#2#g'