如何在文件中两个字符串之间匹配字符串并使用sed操作匹配的字符串?

时间:2019-04-30 17:52:09

标签: bash

我正在尝试使用sed操作一个包含文本的文件,该程序应匹配两个字符串之间的信息,并在匹配字符串之间的文件中的每一行之前添加一个新空格。

文件的一部分看起来像这样:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
this is example text
this is example text
this is example text

Files:
//network paths
//network paths

我正在尝试操纵此文件以使Description和Files之间的文本匹配,并在匹配的文本的每一行之前引入一个空格。

最终结果应如下所示:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

我已经尝试过此命令:

sed -i -e 's/Description:(^.*)Files:/ / ' filename.txt

它无法正常工作。现在,当我尝试在每行之前添加空白时 sed -i -e 's/^/ /' filename.txt

这很好用,同时在文件中的每一行之前引入了空格。

有人建议指出我要去哪里,以及如何实现预期的解决方案。

3 个答案:

答案 0 :(得分:1)

不太优雅,但是可以。

sed '/^Description:/,/^$/{ /^Description\|^$/b; s/.*/ &/}' file

输出:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

答案 1 :(得分:1)

在两种模式之间,每行的开头都排一个空格。

sed '/^Description:/,/^$/{//!s/^/ /}' file

关于//,在POSIX sed specification中的描述如下:

  

如果RE为空(即未指定任何模式),则sed的行为就像指定了所应用的最后一条命令(作为地址或替代命令的一部分)中使用的最后一个RE。 >

给出示例,其输出如下:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

为了涵盖在Files:之前可能存在空白行的两种情况,可以使用以下方法:

sed '/^Description:/,/^Files:/{//!s/^./ &/}' file

答案 2 :(得分:0)

如果不确定是否可以将空行用作最后一行,则可以

sed '/Description:/,/Files:/ s/^/ /; s/ \(Description\|Files\):/\1:/' file

d="Description"
f="Files"
sed "/$d:/,/$f:/ s/^/ /; s/ \($d\|$f\):/\1:/" file