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 關注
- 1106 瀏覽
添加回答
舉報