上古神器sed命令(上)
测试文档:(people.txt)
Jack is 18-year old, he comes from US.
Mike is 16-year old, he comes from Canada.
Chen is 21-year old, he comes from China.
Lau is 18-year old, he comes from HongKong.
Michael is 20-year old, he comes from UK.
Phoebe is 18-year old, she comes from Australie.
s参数
“s/old/new/” | “2s/-year/years/” | “2,5s/-year/years/” |
---|---|---|
首次出现的更改 | 第2行的”-year”改成” years”首次出现更改 | 2到5行修改 |
1,替换:
例如,将首次出现的”-year”改成” years”,第二次出现的或第三次出现的不用改:
sed "s/-year/years/" people.txt
Jack is 18years old, he comes from US.
Mike is 16years old, he comes from Canada.
Chen is 21years old, he comes from China.
Lau is 18years old, he comes from HongKong.
Michael is 20years old, he comes from UK.
Phoebe is 18years old, she comes from US.
2,指定某些行替换:
例如,将第2行的”-year”改成” years”,(只更改第二行)首次出现更改:
sed "2s/-year/years/" people.txt
Jack is 18-year old, he comes from US.
Mike is 16years old, he comes from Canada.
Chen is 21-year old, he comes from China.
Lau is 18-year old, he comes from HongKong.
Michael is 20-year old, he comes from UK.
Phoebe is 18-year old, she comes from Australie.
再如,将第2至5行的”-year”改成” years”:
sed "2,5s/-year/years/" people.txt
Jack is 18-year old, he comes from US.
Mike is 16years old, he comes from Canada.
Chen is 21years old, he comes from China.
Lau is 18years old, he comes from HongKong.
Michael is 20years old, he comes from UK.
Phoebe is 18-year old, she comes from Australie.
3,替换每一行中的第2个小写s成大写S:
sed "s/s/S/2" people.txt
i参数
1,直接通过sed修改原文,加选项 -i:
sed -i "2s/-year/years/" people.txt
注意:sed缺省状态下不会修改原文
g参数(会匹配里面所有内容)
1,替换每一行中的所有的小写s成大写S:
sed "s/s/S/g" people.txt
Jack iS 18-year old, he comeS from US.
Mike iS 16-year old, he comeS from Canada.
Chen iS 21-year old, he comeS from China.
Lau iS 18-year old, he comeS from HongKong.
Michael iS 20-year old, he comeS from UK.
Phoebe iS 18-year old, She comeS from AuStralie.
注意:g的意思是一行中所有的匹配项,否则缺省只会匹配第一个s
2,替换每一行中的第2个以后的小写s成大写S:
sed "s/s/S/2g" people.txt
Jack is 18-year old, he comeS from US.
Mike is 16-year old, he comeS from Canada.
Chen is 21-year old, he comeS from China.
Lau is 18-year old, he comeS from HongKong.
Michael is 20-year old, he comeS from UK.
Phoebe is 18-year old, She comeS from AuStralie.