三:增删换显几个练习
例:cat 1.txt
cat 1.txt
12332###DISO###45.12^M
00332###LPSO###23.14^M
01299###USPD###34.46^M
把所有是#的内容替换掉
sed 's/##*//' 1.txt
12332DISO45.12^M
00332LPSO23.14^M
01299USPD34.46^M
显示第2行内容
sed -n '2p' 1.txt
00332###LPSO###23.14^M
删除所有行首是0 的行内容
sed /^00*/d 1.txt
12332###DISO###45.12^M
替换行首是0的内容为1
sed 's/^0/1/g' 1.txt
12332###DISO###45.12^M
10332###LPSO###23.14^M
11299###USPD###34.46^M
替换行尾是特殊字符^M
sed 's/\^M$//g' 1.txt
12332###DISO###45.12
00332###LPSO###23.14
01299###USPD###34.46
操作集合
cat 1.txt |sed 's/##*//g' | sed 's/\^M//g' | sed '2d' | sed '/^0/i hello' | sed '/^0/a word' | sed '1p'
12332DISO45.12
12332DISO45.12
hello
01299USPD34.46
word
看到前两行是同样的内容输出,如果我们想要输出匹配的一行. 用-n 参数; 如果想要让上面的内容生效用-i 参数
四:打印行号
例 :cat 2.txt
cat 2.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid art and company.
The office Dibble art played well.
The local nurse music P.Neave was in attendance.
sed -e '/was/=' 2.txt
The honeysuckle band played all night long for only $90.
2
It was an evening of splendid art and company.
The office Dibble art played well.
4
The local nurse music P.Neave was in attendance.
如果只关心行号 把-e换成-n
只显示匹配到的行和行号
sed -n -e '/was/p' -e '/was/=' 2.txt
It was an evening of splendid art and company.
2
The local nurse music P.Neave was in attendance.
4
五:读入文件内容,写入文件内容
cat 1.txt
12332###DISO###45.12^M
00332###LPSO###23.14^M
01299###USPD###34.46^M
cat 2.txt
The honeysuckle band played all night long for only $90.
It was an evening of splendid art and company.
The office Dibble art played well.
The local nurse music P.Neave was in attendance.
把2.txt中的内容读入1.txt第一行下面
sed '1r 2.txt' 1.txt
12332###DISO###45.12^M
The honeysuckle band played all night long for only $90.
It was an evening of splendid art and company.
The office Dibble art played well.
The local nurse music P.Neave was in attendance.
00332###LPSO###23.14^M
01299###USPD###34.46^M
把1.txt第1行写入test.txt中
sed '1w test.txt' 1.txt
cat test.txt
12332###DISO###45.12^M