加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash打印转义文件内容

发布时间:2020-12-15 22:11:05 所属栏目:安全 来源:网络整理
导读:我正在尝试使用转义双引号打印文件内容. # read file contents from ${filename}# - escape double quotes# - represent newlines as 'n' # print the resultecho "my file contents: "${out}"" 例如,如果我的文件是 empty lineconsole.log("hello,world"
我正在尝试使用转义双引号打印文件内容.

# 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>

它应该打印

my file contents: "nconsole.log("hello,world");n"

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

解决方法

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

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

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

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

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

echo "file contents: $(jq -Rs . <file)"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读