替换文本中的段落

时间:2016-09-27 16:33:16

标签: bash awk sed

如何使用shell命令(sed或awk)替换文件中的段落,如下所示:

bala bala ba1
balabala.
leave me here.

this paragraph
yes, I'm going
to be replaced

The rest contains
should not be replaced.

更换后:

bala bala ba1
balaba.
leave me here.

New contains,
I'm replacement!

The rest contains
should not be replaced.

我声明原始文件包含在变量$OLD中,而new包含在另一个变量$NEW中。

1 个答案:

答案 0 :(得分:4)

假设您有包含新旧段落的变量,如

$ echo "$old"
this paragraph
yes, I'm going
to be replaced

$ echo "$new"
New contains,
I'm replacement!

您可以将文件(假设它被称为infile)读入Bash变量并使用参数扩展:

$ contents=$(< infile)
$ echo "${contents/$old/$new}"
bala bala ba1
balabala.
leave me here.

New contains,
I'm replacement!

The rest contains
should not be replaced.

要就地更改文件:

echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile