如何使用转义字符(\ n)将多行文件显示为单个字符串 [英] How to display a file with multiple lines as a single string with escape chars (\n)
本文介绍了如何使用转义字符(\ n)将多行文件显示为单个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在bash中,如何显示多行文件的内容作为单个字符串,其中新行显示为\n
.
In bash, how I can display the content of a file with multiple lines as a single string where new lines appears as \n
.
示例:
$ echo "line 1
line 2" >> file.txt
我需要使用bash命令获取此"line 1\nline2"
的内容.
I need to get the content as this "line 1\nline2"
with bash commands.
我尝试使用cat/printf/echo
的组合,但没有成功.
I tried using a combinations of cat/printf/echo
with no success.
推荐答案
您可以使用bash的printf
关闭内容:
You can use bash's printf
to get something close:
$ printf "%q" "$(< file.txt)"
$'line1\nline2'
,在bash
4.4中,有一个新的参数扩展运算符可产生相同的结果:
and in bash
4.4 there is a new parameter expansion operator to produce the same:
$ foo=$(<file.txt)
$ echo "${foo@Q}"
$'line1\nline2'
这篇关于如何使用转义字符(\ n)将多行文件显示为单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文