【发布时间】:2017-02-16 13:12:15
【问题描述】:
假设我有以下文件:
hello\nworld
也就是说,字符串\n 确实存在于文件中:
$ cat input.txt
hello\nworld
我想将这个文件完全像读取到 shell 中的变量一样。但是,从文件中读取数据的所有常用方法,例如 here 中描述的那些方法,都会使 shell 将 \n 序列解释为换行符:
% test="$(<input.txt)"
% echo "$test"
hello
world
% test="$(cat input.txt)"
% echo "$test"
hello
world
这完全出乎我的意料,坦率地说,我很困惑,我在互联网上找不到这个问题的答案;我预计有人已经被这个问题绊倒了。
我还看到,如果你在逐行读取文件时使用read -r,它可以工作,但我不想逐行读取,我想读取整个文件。具体来说,我希望这里的 test 变量包含字符串 "hello\nworld" 字面意思。我该怎么做?
【问题讨论】:
-
您的
echo是否别名为echo -e? -
@gudok 不,不是。
-
type echo和which echo告诉我们什么? -
读取文件不是问题;
echo是,因为zsh遵循 POSIX 规范来扩展\n但bash没有。请改用printf '%s' "$test"。 -
@Yarden 以上是正确的。反引号不显示,但这是相同的:
VAR=$(cat file)- 即test=$(cat input.txt)