用sed替换多行

时间:2014-12-29 06:33:50

标签: sed

我在sample.txt中有以下内容

abc
efg
hij
klm
nop
qrs

我尝试用{/ p>替换其他文字abc

sed -i '/abc/c\This line is removed by the admin.' sample.txt

输出:

This line is removed by the admin.
efg
hij
klm
nop
qrs

它只能用于一行。

但我想知道如何使用sed替换一组给定的1到3行?

4 个答案:

答案 0 :(得分:0)

如果您知道行号,则将它们添加到您的模式中,如下所示:

sed -i '4 s/abc/c\This line is removed by the admin./' sample.txt

以上内容将更改第4行。如果您想更改范围(例如第5-10行),请在逗号之间输入起始和结束行号:

sed -i '5,10 s/abc/c\This line is removed by the admin./' sample.txt

$表示文件中的最后一行,所以如果你想说,那么100行到最后:

sed -i '100,$ s/abc/c\This line is removed by the admin./' sample.txt

您可能会发现此link有用。查看Ranges by line number上的部分。

答案 1 :(得分:0)

如果您的唯一标准是行号,那么您可以像这样指定它们:

sed -i '1,3 s/.*/This line is removed by the admin./' sample.txt

答案 2 :(得分:0)

如果您想尝试,请参阅以下awk解决方案:

awk 'NR>=1 && NR<=3 {$0="This line is removed by the admin."}1' file
This line is removed by the admin.
This line is removed by the admin.
This line is removed by the admin.
klm
nop
qrs

将其写回文件

awk 'NR>=1 && NR<=3 {$0="This line is removed by the admin."}1' file > tmp && mv tmp file

答案 3 :(得分:0)

这可能适合你(GNU sed):

sed '1,3c\replace lines 1 to 3 with this single line' file

如果要替换范围内的每一行,请使用:

sed $'1,3{\\athis replaces the original line\nd}' file

或者可能更容易:

sed '1,3s/.*/this replaces the original line/' file