如何在sed中只搜索第一个模式范围

如何在sed中只搜索第一个模式范围,sed,Sed,我的输入文件如下所示 Start1 some text that I want modified Pattern1 some other text which I do not want to modify End1 Start1 Pattern2 End1 /Start1/,/Pattern1/c\ Start1\ Modification text here\ Pattern1\ additional modifications 我的sed模式是这样的 Start1 some text

我的输入文件如下所示

Start1
some text
that I want
modified
Pattern1
some other text
which I do not want
to modify
End1

Start1
Pattern2
End1
/Start1/,/Pattern1/c\
Start1\
Modification text here\
Pattern1\
additional modifications
我的sed模式是这样的

Start1
some text
that I want
modified
Pattern1
some other text
which I do not want
to modify
End1

Start1
Pattern2
End1
/Start1/,/Pattern1/c\
Start1\
Modification text here\
Pattern1\
additional modifications
我只想修改
Start1
End1
第一个范围内的文本。 另外,我还指定了第二个范围中不存在的
Pattern1

我跑

预期结果

Start1
Modification text here
Pattern1
additional modifications
some other text
which I do not want
to modify
End1

Start1
Pattern2
End1
试试这个

sed ':A;/Start1/!b;N;/Pattern1/!bA;s/\(Start1\n\)\(.*\)\(\nPattern1\)/\1Modification text here\3\nadditional modifications/' infile
试试这个

sed ':A;/Start1/!b;N;/Pattern1/!bA;s/\(Start1\n\)\(.*\)\(\nPattern1\)/\1Modification text here\3\nadditional modifications/' infile
在GNU sed中:

  • sed-e'/START/,/END/c TEXT
不一样

  • sed-e'/START/,/END/{c TEXT'-e'}'
第一个将开始从输出流中省略范围,并在到达范围的末尾时向输出字符串中发出一个
TEXT
实例。第二行将用
文本
替换范围内的每一行

您的问题是,第二个范围从输出流中被忽略,即使您从未到达第二个范围的末尾
/START/,/END/c
其中从未出现的
/END/
基本上类似于
/START/,$d

我能想到的唯一解决方案是笨重的:

/Start1/,/Pattern1/{ /Pattern1/{ # Insert into output stream i\ Start1\ Modification text here\ Pattern1\ additional modifications # Read in the rest of the file :a $!N $!ba # Remove the original Pattern1 line from the pattern space # (Remove first line and newline of pattern space) s/^[^\n]*\n// # Print pattern space and quit q } # Delete lines in the range other than /Pattern1/ d } /Start1/,/Pattern1/{ /模式1/{ #插入到输出流中 我\ Start1\ 此处为修改文本\ 模式1\ 附加修改 #读入文件的其余部分 :a $!N $!ba #从阵列空间中删除原始阵列1线 #(删除图案空间的第一行和换行符) s/^[^\n]*\n// #打印图案空间并退出 Q } #删除除/Pattern1之外的范围内的行/ D } 在GNU sed中:

  • sed-e'/START/,/END/c TEXT
不一样

  • sed-e'/START/,/END/{c TEXT'-e'}'
第一个将开始从输出流中省略范围,并在到达范围的末尾时向输出字符串中发出一个
TEXT
实例。第二行将用
文本
替换范围内的每一行

您的问题是,第二个范围从输出流中被忽略,即使您从未到达第二个范围的末尾
/START/,/END/c
其中从未出现的
/END/
基本上类似于
/START/,$d

我能想到的唯一解决方案是笨重的:

/Start1/,/Pattern1/{ /Pattern1/{ # Insert into output stream i\ Start1\ Modification text here\ Pattern1\ additional modifications # Read in the rest of the file :a $!N $!ba # Remove the original Pattern1 line from the pattern space # (Remove first line and newline of pattern space) s/^[^\n]*\n// # Print pattern space and quit q } # Delete lines in the range other than /Pattern1/ d } /Start1/,/Pattern1/{ /模式1/{ #插入到输出流中 我\ Start1\ 此处为修改文本\ 模式1\ 附加修改 #读入文件的其余部分 :a $!N $!ba #从阵列空间中删除原始阵列1线 #(删除图案空间的第一行和换行符) s/^[^\n]*\n// #打印图案空间并退出 Q } #删除除/Pattern1之外的范围内的行/ D }
发布最终预期结果发布最终预期结果