3 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
解決方案是使用$'string',例如:
$ STR=$'Hello\nWorld'
$ echo "$STR"
Hello
World
以下是Bash手冊(cè)頁的摘錄:
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貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
Echo是九十年代,充滿了危險(xiǎn),它的使用應(yīng)該導(dǎo)致核心轉(zhuǎn)儲(chǔ)不低于4GB。說真的,echo的問題是Unix標(biāo)準(zhǔn)化過程最終發(fā)明printf實(shí)用程序的原因,消除了所有問題。
所以要在字符串中獲取換行符:
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轉(zhuǎn)義序列。大家請(qǐng)printf現(xiàn)在使用,永遠(yuǎn)不要回頭。

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
我根據(jù)其他答案做了什么
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 關(guān)注
- 1095 瀏覽
添加回答
舉報(bào)