sed字符串修改
如果需要修改某一行的内容,可以使用c
(change)去修改。比如上面的data文件
,内容为:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
1 修改指定的某一行
比如要修改第三行的内容修改为changed line 3
,输入:
sed '3c\changed line 3' data
运行后结果为:
This is line 1
This is line 2
changed line 3
This is line 4
This is line 5
This is line 6
2 指定字符串去匹配并修改
比如把包含line 3
的行改成changed line 3
,输入:
sed '/line 3/c\changed line 3' data
运行后结果为:
This is line 1
This is line 2
changed line 3
This is line 4
This is line 5
This is line 6
3 字符转换
字符转换可以一个一个地对字符进行转换,输入模式为:
sed 'y/src/dst/' data
这个命令会把src的第一个字符转化成dst的第一个字符,src的第二个字符转化成dst的第二个字符,依次类推。当发现src和dst的长度不同时,该命令报错。比如value文件的内容为:
This is line 1, num is 134
This is line 2, num is 158
This is line 3, num is 238
This is line 4, num is 849
This is line 5, num is 666
This is line 6, num is 899
现在想把所有的2
换成7
,所有的3
换成8
,所有的4
换成9
,输入:
sed 'y/234/789/' value
运行后输出结果为:
This is line 1, num is 189
This is line 7, num is 158
This is line 8, num is 788
This is line 9, num is 899
This is line 5, num is 666
This is line 6, num is 899
可以发现,y指令会把搜索所有的对应字符,而不需要加g去全局替换