我有几行文件。 当在shell中使用cat / more / less [file]时,
内容逐行显示
在执行以下命令时:
temp=`cat [file]` echo $temp
内容显示在一行中。
当设置为环境variables然后回显时,是否有办法保留行结束符?
谢谢
是:
temp=`cat [file]` echo "$temp"
神奇的是在$temp
周围的引号; 没有他们, echo
得到这些论点:
echo line1\nline2\nlin3
shell解析算法将在空白处分割命令行,所以echo
看到三个参数。 如果引用该变量,则echo
将会看到一个参数,而shell解析将不会触及引号之间的空格。
这是一个超精确的答案:将变量替换为变量不会保留:
只有后者可以解决:
temp=$(realprocess; echo x) ## Add x to the end to preserve trailing newlines temp=${temp%x} ## Remove the x again (keeping originally trailing newlines)
当你想显示一个变量的真实内容时,使用printf
。 echo
增加了一个额外的换行符,并不可靠(例如,当输入以字符串-n
开始时)。
在任何情况下,总是引用你的变量,或者shell将它们分割成任意数量的参数!
printf %s "$temp"
通常,将文件的完整内容保存在shell变量中并不是您想要的。 有这个文件。
如果我做了以下事情,换行符被保留:
echo a >> test echo b >> test temp=`cat test` echo $temp