bash打印转义文件内容

Pet*_*rov 4 bash printf cat

我正在尝试使用转义双引号打印文件内容.

# read file contents from ${filename}
# - escape double quotes
# - represent newlines as '\n' 
# print the result
echo "my file contents: \"${out}\""
Run Code Online (Sandbox Code Playgroud)

例如,如果我的文件是

<empty line>
console.log("hello, world");
<empty line>
Run Code Online (Sandbox Code Playgroud)

它应该打印

my file contents: "\nconsole.log(\"hello, world\");\n"
Run Code Online (Sandbox Code Playgroud)

我试图使用带有%q格式说明符的printf,但是它存在删除尾随空格的问题.

Cha*_*ffy 5

只做你明确要求的两个文字转换:

IFS= read -r -d '' content <file
content=${content//'"'/'\"'/}
content=${content//$'\n'/'\n'}
echo "file contents: $content"
Run Code Online (Sandbox Code Playgroud)

也就是说,如果您尝试将任意内容表示为JSON字符串,请让完全兼容的JSON解析器/生成器完成繁重的工作:

IFS= read -r -d '' content <file
echo "file contents: $(jq -n --arg content "$content" '$content')"
Run Code Online (Sandbox Code Playgroud)

...或者,甚至更好(为了支持具有bash无法存储为字符串的内容的文件),让我们jq直接从输入文件中读取:

echo "file contents: $(jq -Rs . <file)"
Run Code Online (Sandbox Code Playgroud)