bash打印转义文件内容

bash打印转义文件内容,bash,printf,cat,Bash,Printf,Cat,我正试图用转义双引号打印文件内容 # read file contents from ${filename} # - escape double quotes # - represent newlines as '\n' # print the result echo "my file contents: \"${out}\"" 例如,如果我的文件是 <empty line> console.log("hello, world"); <empty line> 我试图

我正试图用转义双引号打印文件内容

# read file contents from ${filename}
# - escape double quotes
# - represent newlines as '\n' 
# print the result
echo "my file contents: \"${out}\""
例如,如果我的文件是

<empty line>
console.log("hello, world");
<empty line>

我试图将printf与%q格式说明符一起使用,但出现问题,它删除了尾随空格。

命令替换带尾随换行符。可以通过添加虚拟非换行字符,然后将其剥离来防止出现这种情况:

printf '\n\nfoo\n\n' > file

contents="$(cat "file"; printf x)"
contents="${contents%x}"

printf "The shell equivalent of the file contents is: %q\n" "$contents"

如果您试图生成JSON,则应使用
jq

只执行您明确要求的两种文字转换:

IFS= read -r -d '' content <file
content=${content//'"'/'\"'/}
content=${content//$'\n'/'\n'}
echo "file contents: $content"

在我看来,将任意多行文本转换为printf格式最可靠的方法是使用bash内置的printf

$ nl -ba testfile
     1
     2  console.log("hello, world");
     3
$ s="$(printf '%q' "$(cat testfile; printf x)")"
$ s="${s%x\'}"; s="${s#\$\'}"
$ echo "$s"
\nconsole.log("hello, world");\n\n
这具有处理所有字符的优势,包括CRs和制表符,而不仅仅是换行符


请注意我们用来避免剥离尾随换行符的有趣的命令扩展解决方案。(否则,我们可以只
s=“$(printf'%q'”$(哇,这是一个非常不寻常的壮举。为什么?[如果你愿意,我可以为它编写一个C程序]展示你是如何尝试
printf%q
——我向你保证,它本身不会删除尾随空格。如果你是在命令替换中运行它(或者以那种方式运行
cat
),另一方面……另外,另一个人有权使用它——如果你试图生成JSON,请使用为这项工作构建的工具。@PaulStelian我也可以用C来完成;)我想要一个简短的脚本this@PetrPetrov,这是正确的,因为
$(cat文件)
本身删除尾随的换行符。相反,请尝试:
IFS=read-r-d''内容我也知道使用
IFS=read-r-d''内容作为
console.log()
是JavaScript源代码,OP所需的输出极有可能是一个JavaScript字符串。
printf%q
今天可能适用于此(我不是在没有分析的情况下断言这是真的),但不能保证它在将来会起作用——如果bash明天引入新的扩展报价表单,
printf%q
将在规范范围内使用该扩展报价表单。
IFS= read -r -d '' content <file
echo "file contents: $(jq -n --arg content "$content" '$content')"
echo "file contents: $(jq -Rs . <file)"
$ nl -ba testfile
     1
     2  console.log("hello, world");
     3
$ s="$(printf '%q' "$(cat testfile; printf x)")"
$ s="${s%x\'}"; s="${s#\$\'}"
$ echo "$s"
\nconsole.log("hello, world");\n\n