用多行变量替换替换行

问题描述 投票:3回答:2

我正在尝试用存储在变量中的多行字符串替换文件中的单行。当打印到屏幕上时,我能够获得正确的结果,但是如果我想进行“就地”替换,则无法获得正确的结果。

文件格式:

*some code*
*some code*
string_to_replace
*some code*

我希望生成的文件为:

*some code*
*some code*
line number 1
line number 2
line number 3
*some code*

我尝试的代码是:

new_string="line number 1\nline number 2\nline number 3"

# Correct output on screen
sed -e s/"string_to_replace"/"${new_string}"/g $file

# Single-line output in file: "line number 1line number 2line number 3"
sed -i s/"string_to_replace"/"${new_string}"/g $file

[当尝试组合-i和-e选项时,结果与仅使用-i时的结果相同。有人可以帮我解决这个问题吗?

我在CentOS上使用GNU sed版本4.1.5(通过Mac上的ssh连接到它)

bash sed multiline
2个回答
1
投票

sed中,您可以双引号命令字符串,然后让Shell为您扩展,如下所示:

new_string="line number 1\nline number 2\nline number 3"
sed -i "s/string_to_replace/$new_string/" file

0
投票

尽管您已经特别要求sed,但是您可以使用awk通过使用以下命令将多行变量存储在文件中来完成此操作

awk '/string_to_replace/{system("cat file_with_multiple_lines");next}1' file_to_replace_in > output_file
© www.soinside.com 2019 - 2024. All rights reserved.