在bash脚本中,我需要用一些heredoc替换文件中的占位符字符串。我该怎么做?
e.g。 sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt
其中
<<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC
答案 0 :(得分:2)
通过临时文件并避免替换,因为可能发生替换模式特殊字符的行为(如&
,\x
)
所以
cat > /tmp/HereFile <<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC
sed '/PLACEHOLDER_TEXT/ {
r /tmp/HereFile
d
}' YourFile
rm /tmp/HereFile
答案 1 :(得分:1)
将其展平(您可以更改#,如果数据可能出现在您的数据中),然后将新行重新放入其中:
sed "s/PLACEHOLDER_TEXT/$(echo "$HEREDOC"|tr "\n" "#")/g;s/#/\n/g" file.txt
构建$ HEREDOC变量:
$> export HEREDOC=$(cat<<EOF
> what is going
> on with
> this
> thing
> EOF
> )
答案 2 :(得分:0)
尝试此命令:
val=$(tr '\n' ' ' < PlaceHolderText.txt); sed "s/PLACEHOLDER/$val/" File.txt
示例:
sdlcb@Goofy-Gen:~/AMD$ cat PlaceHolderText.txt
Some multiple
lines of
text to replace
sdlcb@Goofy-Gen:~/AMD$ cat File.txt
This is a text with PLACEHOLDER for some additional data.
sdlcb@Goofy-Gen:~/AMD$ val=$(tr '\n' ' ' < PlaceHolderText.txt); echo $val; sed "s/PLACEHOLDER/$val/" File.txt
This is a text with Some multiple lines of text to replace for some additional data.