如何使用带有前导空格的展示位置替换sed中的多行字符串

时间:2022-05-17 16:48:33

I have a file with lines like

我有一个像行的文件

 something 
-----------

where there's a leading and trailing space after something. I want to replace it with

什么东西之后有一个领先和尾随的空间。我想用它替换它

 other 
-------

and preserve the leading and trailing space. How?

并保留领先和尾随空间。怎么样?

3 个解决方案

#1


1  

This might work for you (GNU sed):

这可能适合你(GNU sed):

sed -i '/^ something $/{:a;N;/^--*$/M!ba;s/something/other/}' file

Gather up lines between the start and end markers, then replace the required string with the alternative.

收集开始和结束标记之间的行,然后用替代标记替换所需的字符串。

N.B. Uses the M flag to make an exact match within multiple lines.

注:使用M标志在多行中进行精确匹配。

#2


1  

sed is for simple substitutions on individual lines, that is all, for anything else you should be using awk:

sed用于单独行的简单替换,也就是说,除了你应该使用awk的任何其他内容:

$ awk 'n{$0=substr($0,1,n); n=0} {sub(/^ something $/," other "); n=length()}1' file
 other
-------

That will work with any awk in any shell on any UNIX box.

这适用于任何UNIX机器上任何shell中的任何awk。

#3


0  

sed can match multiple lines with a comma separated set of regexps. And substitute everything in the range with the c command. To get the c command not to ignore leading white space, use a backslash after it. e.g.

sed可以使用逗号分隔的正则表达式匹配多行。并使用c命令替换范围内的所有内容。要使c命令不忽略前导空格,请在其后使用反斜杠。例如

sed -i.original '/^ something $/,/-----------$/c\ other \n-------' input-filename

#1


1  

This might work for you (GNU sed):

这可能适合你(GNU sed):

sed -i '/^ something $/{:a;N;/^--*$/M!ba;s/something/other/}' file

Gather up lines between the start and end markers, then replace the required string with the alternative.

收集开始和结束标记之间的行,然后用替代标记替换所需的字符串。

N.B. Uses the M flag to make an exact match within multiple lines.

注:使用M标志在多行中进行精确匹配。

#2


1  

sed is for simple substitutions on individual lines, that is all, for anything else you should be using awk:

sed用于单独行的简单替换,也就是说,除了你应该使用awk的任何其他内容:

$ awk 'n{$0=substr($0,1,n); n=0} {sub(/^ something $/," other "); n=length()}1' file
 other
-------

That will work with any awk in any shell on any UNIX box.

这适用于任何UNIX机器上任何shell中的任何awk。

#3


0  

sed can match multiple lines with a comma separated set of regexps. And substitute everything in the range with the c command. To get the c command not to ignore leading white space, use a backslash after it. e.g.

sed可以使用逗号分隔的正则表达式匹配多行。并使用c命令替换范围内的所有内容。要使c命令不忽略前导空格,请在其后使用反斜杠。例如

sed -i.original '/^ something $/,/-----------$/c\ other \n-------' input-filename