3 回答
TA贡献1821条经验 获得超6个赞
解决方案是使用$'string',例如:
$ STR=$'Hello\nWorld'
$ echo "$STR"
Hello
World
以下是Bash手册页的摘录:
Words of the form $'string' are treated specially. The word expands to
string, with backslash-escaped characters replaced as specified by the
ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
\a alert (bell)
\b backspace
\e
\E an escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\' single quote
\" double quote
\nnn the eight-bit character whose value is the octal value
nnn (one to three digits)
\xHH the eight-bit character whose value is the hexadecimal
value HH (one or two hex digits)
\cx a control-x character
The expanded result is single-quoted, as if the dollar sign had not
been present.
A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. If the
current locale is C or POSIX, the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.
TA贡献1770条经验 获得超3个赞
Echo是九十年代,充满了危险,它的使用应该导致核心转储不低于4GB。说真的,echo的问题是Unix标准化过程最终发明printf实用程序的原因,消除了所有问题。
所以要在字符串中获取换行符:
FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"
那里!没有SYSV和BSD回声疯狂,一切都得到了整齐的打印和完全便携式支持C转义序列。大家请printf现在使用,永远不要回头。
TA贡献1946条经验 获得超4个赞
我根据其他答案做了什么
NEWLINE=$'\n'
my_var="__between eggs and bacon__"
echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"
# which outputs:
spam
eggs__between eggs and bacon__bacon
knight
- 3 回答
- 0 关注
- 1059 浏览
添加回答
举报