简体   繁体   English

我如何使用sed选择性替换某些行

[英]How do I use sed for selective replacement of certain lines

I have text as follows in file: 我在文件中有以下文本:

Line 1
Line 2
WORD1
Line3
Line 4
WORD2
Line5

I would like to replace all lines between WORD1 and WORD2 to produce final output: 我想替换WORD1和WORD2之间的所有行以产生最终输出:

Line 1
Line 2
NEW
LINES
XXXXX
Line5

With sed '/WORD1/,/WORD2/d' input.txt I can remove the lines, but how can I replace them instead of deleting them? 使用sed '/WORD1/,/WORD2/d' input.txt可以删除行,但是如何替换而不是删除行呢?

One way: 单程:

Replacement text file: 替换文本文件:

$ cat rep
NEW
LINES
XXXXX

Input file: 输入文件:

$ cat file
Line 1
Line 2
WORD1
Line3
Line 4
WORD2
Line5

sed command: sed命令:

$ sed '/WORD1/,/WORD2/{
> /WORD2/r rep
> d
> }' file

The sed command seraches for the line range WORD1 till WORD2 and deletes those lines(d) , and when WORD2 is encounterd, it dumps the replacement file contents(r rep). sed命令搜索WORD1到WORD2的行范围,并删除这些行(d),当遇到WORD2时,它将转储替换文件的内容(r rep)。

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed '/WORD1/,/WORD2/c\NEW\nLINES\nXXXXX' file

This uses the range match and the c (change) command. 这使用范围匹配和c (更改)命令。

如果awk没问题,请尝试以下操作:

awk '/WORD1/{p=1; print "NEW\nLINES\nXXXXX"}; !p; /WORD2/{p=0}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM