首页 > 解决方案 > Linux:如何替换两行之间的所有文本并使用 sed 将其替换为变量的输出?

问题描述

我有一个与此 SO 线程非常相似的问题:如何替换两点之间的所有行并将其替换为 sed 中的一些文本

考虑这样一个问题:

$ cat file
BEGIN
hello
world
how
are
you
END

$ sed -e '/BEGIN/,/END/c\BEGIN\nfine, thanks\nEND' file
BEGIN
fine, thanks
END

我如何将已保存的文本注入到变量中,例如:

str1=$(echo "This is a test")

如何在 的位置注入 str1 的输出fine, thanks,例如:

sed -e '/BEGIN/,/END/c\BEGIN\n$str1\nEND' file  # fails to work as hoped

我还想保存输出以覆盖文件。

标签: linuxsed

解决方案


当然是容易的awk

鉴于:

cat file
ABC
BEGIN
hello
world
how
are
you
END
XYZ

你可以做:

str='TEST'

awk -v r="$str" -v f=1 '/^BEGIN$/{print $0 "\n" r; f=0}
/^END$/{f=1} f' file

印刷:

ABC
BEGIN
TEST
END
XYZ

如果要在这些标记之间嵌入另一个文件:

awk -v f=1 -v fn='ur_file' '/^BEGIN$/{
    print $0
    while ((getline<fn)>0) {print}
    f=0}
/^END$/{f=1} f' file

推荐阅读