在bash腳本中,我需要用一些heredoc替換文件中的佔位符字符串。我怎麼做?在bash中使用sed替換heredoc字符串
例如sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt
其中
<<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC
在bash腳本中,我需要用一些heredoc替換文件中的佔位符字符串。我怎麼做?在bash中使用sed替換heredoc字符串
例如sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt
其中
<<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC
通trhough一個臨時文件,並避免的替代品,由於更換圖案特殊字符的行爲可能發生(如&
,\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
只需壓平(你可以改變#如果可能會出現在你的數據),並把新行早在以後類似:
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
>)
試試這個命令:
val=$(tr '\n' ' ' < PlaceHolderText.txt); sed "s/PLACEHOLDER/$val/" File.txt
實施例:
[email protected]:~/AMD$ cat PlaceHolderText.txt
Some multiple
lines of
text to replace
[email protected]:~/AMD$ cat File.txt
This is a text with PLACEHOLDER for some additional data.
[email protected]:~/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.
你應該不要使用過時的過時背景,使用像這樣的括號:'val = $(tr .....)' – Jotne 2014-11-06 06:51:51
非常感謝! – Dave 2014-11-06 21:09:57