简体   繁体   English

在bash中使用sed将字符串替换为heredoc

[英]Use sed in bash to replace string with heredoc

In a bash script I need to replace a placeholder string in a file with some heredoc. 在bash脚本中,我需要用一些heredoc替换文件中的占位符字符串。 How do I do that? 我怎么做?

eg sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt where 例如sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt其中

<<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC

pass trhough a temporary file and avoid a substitute due to behavior of replace pattern special char that can occur (like & , \\x ) 通过临时文件传递,并避免由于可能发生的替换模式特殊字符的行为而导致替换(如&\\x

so 所以

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 

Just flatten it out (you can change the # if that may appear in your data) and put the newlines back in afterward like: 只需弄平(如果可能出现在数据中,则可以更改#),然后将换行符放回去,例如:

sed "s/PLACEHOLDER_TEXT/$(echo "$HEREDOC"|tr "\n" "#")/g;s/#/\n/g" file.txt

To build the $HEREDOC variable: 要构建$ HEREDOC变量:

$> export HEREDOC=$(cat<<EOF

    > what is going 
    > on with 
    > this 
    > thing
    > EOF
    > )

Try this command: 试试这个命令:

val=$(tr '\n' ' ' < PlaceHolderText.txt); sed "s/PLACEHOLDER/$val/" File.txt

Example: 例:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM