This
STR="Hello\nWorld"
echo $STR
作为输出产生
Hello\nWorld
而不是
Hello
World
我应该做什么有一个换行在字符串?
注意:此问题与echo无关。 我知道echo -e,但我正在寻找一种解决方案,允许传递一个字符串(其中包括换行符)作为参数到其他命令,没有类似的选项来解释\n的换行符。
This
STR="Hello\nWorld"
echo $STR
作为输出产生
Hello\nWorld
而不是
Hello
World
我应该做什么有一个换行在字符串?
注意:此问题与echo无关。 我知道echo -e,但我正在寻找一种解决方案,允许传递一个字符串(其中包括换行符)作为参数到其他命令,没有类似的选项来解释\n的换行符。
当前回答
我发现-e标志优雅而直接
bash$ STR="Hello\nWorld"
bash$ echo -e $STR
Hello
World
如果字符串是另一个命令的输出,我只使用引号
indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"
其他回答
我根据其他答案所做的是
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
如果你正在使用Bash,你可以在一个特别引用的$'string'中使用反斜杠转义。例如,添加\n:
STR=$'Hello\nWorld'
echo "$STR" # quotes are required here!
打印:
Hello
World
如果你使用的是其他shell,只需在字符串中插入换行符:
STR='Hello
World'
Bash在$ "字符串中识别出许多其他反斜杠转义序列。以下是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.
我对这里的选择都不太满意。这对我来说很管用。
str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")
唯一简单的替代方法是在变量中输入新行: STR = '新的美元 线的 $STR" %s " 新 行
是的,这意味着在代码中需要的地方输入Enter。
有几个新行字符的等价物。 一种常用的表示新行字符的方法。 新行字符的八进制值。 新行字符的十六进制值。
但所有这些都需要一些工具(POSIX printf)的“解释”:
echo -e "new\nline" ### on POSIX echo, `-e` is not required.
printf 'new\nline' ### Understood by POSIX printf.
printf 'new\012line' ### Valid in POSIX printf.
printf 'new\x0Aline'
printf '%b' 'new\0012line' ### Valid in POSIX printf.
因此,这个工具需要用new-line来构建一个字符串:
$ STR="$(printf 'new\nline')"
$ printf '%s' "$STR"
new
line
在某些shell中,序列$'是一个特殊的shell展开。 已知在ksh93, bash和zsh中工作: STR =美元“新\在线” 当然,也可能有更复杂的解决方案: $ echo '6e65770a6c696e650a' | XXD -p -r 新 行
Or
$ echo "new line" | sed 's/ \+/\n/g'
new
line
我不是bash专家,但这个对我来说很管用:
STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1
$STR2
EOF
)
echo "$NEWSTR"
我发现这更容易格式化文本。