bash sed 用多行变量替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6684487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed replace with variable with multiple lines
提问by Andreas
I am trying to replace a word with a text which spans multiple lines. I know that I can simply use the newline character \n to solve this problem, but I want to keep the string "clean" of any unwanted formatting.
我试图用跨越多行的文本替换一个单词。我知道我可以简单地使用换行符 \n 来解决这个问题,但我想保持字符串“干净”的任何不需要的格式。
The below example obviously does not work:
下面的例子显然不起作用:
read -r -d '' TEST <<EOI
a
b
c
EOI
sed -e "s/TOREPLACE/${TEST}/" file.txt
Any ideas of how to achieve this WITHOUT modifying the part which starts with read and ends with EOI?
关于如何在不修改以 read 开头并以 EOI 结尾的部分的情况下实现这一目标的任何想法?
采纳答案by shellter
An interesting question..
一个有趣的问题。。
This may get you closer to a solution for your use case.
这可能会让您更接近针对您的用例的解决方案。
read -r -d '' TEST <<EOI
a\
b\
c
EOI
echo TOREPLACE | sed -e "s/TOREPLACE/${TEST}/"
a
b
c
I hope this helps.
我希望这有帮助。
回答by Toby Speight
Given that you're using Bash, you can use it to substitute \nfor the newlines:
鉴于您使用的是 Bash,您可以使用它来代替\n换行符:
sed -e "s/TOREPLACE/${TEST//$'\n'/\n}/" file.txt
To be properly robust, you'll want to escape /, &and \, too:
为了适当地健壮,您将想要转义/,&并且\:
TEST="${TEST//\/\\}"
TEST="${TEST//\//\/}"
TEST="${TEST//&/\&}"
TEST="${TEST//$'\n'/\n}"
sed -e "s/TOREPLACE/$TEST/" file.txt
If your match is for a whole line and you're using GNU sed, then it might be easier to use its rcommand instead:
如果您的匹配是针对整行并且您使用的是 GNU sed,那么使用它的r命令可能会更容易:
sed -e $'/TOREPLACE/{;z;r/dev/stdin\n}' file.txt <<<"$TEST"
回答by terryy
tricky... but my solution would be :-
棘手......但我的解决方案是:-
read -r -d '' TEST <<EOI
a
b
c
EOI
sed -e "s/TOREPLACE/`echo "$TEST"|awk '{printf("%s\\n", sed -e 's/TOREPLACE/a\
b\
c\
/g' file.txt
);}'|sed -e 's/\\n$//'`/g" file.txt
Important:Make sure you use the correct backticks, single quotes, double quotes and spaces else it will not work.
重要提示:请确保使用正确的反引号、单引号、双引号和空格,否则将不起作用。
回答by Diego Sevilla
You can just write the script as follows:
您可以按如下方式编写脚本:
##代码##A little cryptic, but it works. Note also that the file won't be modified in place unless you use the -ioption.
有点神秘,但它有效。另请注意,除非您使用该-i选项,否则不会就地修改文件。

