在出现另一个字符串后在sed中搜索字符串

在出现另一个字符串后在sed中搜索字符串,sed,Sed,我的输入文件如下所示 Topic1 Some text Topic2 Some text Topic3 Some text 我需要转到主题2,然后将“一些文本”替换为“实际输入” 下面的脚本有效 /Topic2/,/Topic/ { /Some text/c Actual input } 有没有更简单的方法可以做到这一点。我本来希望下面的方法能奏效,但事实并非如此 /Topic2/ { /Some text/c Actual input } 更新:应该说得更清楚。我只寻找基于sed的解决方

我的输入文件如下所示

Topic1
Some text
Topic2
Some text
Topic3
Some text
我需要转到主题2,然后将“一些文本”替换为“实际输入”

下面的脚本有效

/Topic2/,/Topic/ {
/Some text/c
Actual input
}
有没有更简单的方法可以做到这一点。我本来希望下面的方法能奏效,但事实并非如此

/Topic2/ {
/Some text/c
Actual input
}
更新:应该说得更清楚。我只寻找基于sed的解决方案。

使用awk如何

awk 'p&&/Topic/{p=0}/Topic2/{p=1}p{gsub(/Some text/,"foo\nbar\nbla\nline")}7' file
上面我使用了多行替换作为示例,您输入的输出将是:

Topic1
Some text
Topic2
foo
bar
bla
line
Topic3
您可以将替换字符串作为shell变量传递给awk,这样awk one liner将是灵活的。比如:

kent$  r="a
b
c"

kent$  awk -v rep="$r" 'p&&/Topic/{p=0}/Topic2/{p=1}p{gsub(/Some text/,rep)}7' f  
Topic1
Some text
Topic2
a
b
c
Topic3
Some text

下面是一个
gnu awk
解决方案:

awk -v RS="Topic[0-9]*" 'f=="Topic2" {$0="\nActual input\n"} NR>1{print f,$0} {f=RT}' file
Topic1
Some text

Topic2
Actual input

Topic3
Some text
这可能适用于您(GNU-sed):

或:

或者使用Bash:

sed $'/Topic2/,/Topic/{//!d;/Topic2/a\\bla\\nbla\\nbla\n}' file
编辑:


看起来“range”(/start\u range/,/end\u range/)是唯一的方法。我给出的第二个示例不起作用。@user1074593请参见编辑
sed -e '/Topic2/,/Topic/{//!d;/Topic2/r fileb' -e '}' filea
sed $'/Topic2/,/Topic/{//!d;/Topic2/a\\bla\\nbla\\nbla\n}' file
sed $'/Topic2/{:a;n;/Some text/!ba;c\\Actual input\n}' file