将文字直接写入文件,包括特殊字符 [英] Write text to file literally, including special characters

查看:87
本文介绍了将文字直接写入文件,包括特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用bash脚本将文本写到文件中,而无需修改特殊字符.我搜索类似于以下内容的函数或命令:

I want to write text to file in a bash script, literally and without modifying special characters. I search a function or command similarly to:

echo'line1
line2' > destination/file

,但在文本$'(等)中包含所有特殊字符,而无需修改这些字符.

but including all special characters inside text $ ' " (etc) and without modifying these characters.

推荐答案

最简单的方法是在本文中加引号:

Easiest way is with a quoted heredoc:

cat << 'EOT' > /path/to/file
Thi$ is text with ' " special chars
that [ spans ] {} multiple lines
EOT

请注意,字符串"EOT"是完全任意的,如果要在输出中仅包含字符串EOT的行,则可以选择其他定界符.您还可以堆叠此处的文档,因此,如果要对某些变量进行插值,则可以执行以下操作:

Note that the string "EOT" is completely arbitrary, and if you want a line in the output that consists only of the string EOT, you can choose a different delimiter. You can also stack the here docs, so if you want some variables to be interpolated you can do something like:

{ cat << 'EOT'; cat << EOF; } > /path/to/file
This $var will not be interpolated in the output
EOT
But this $var will!
EOF

这篇关于将文字直接写入文件,包括特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆