gpt4 book ai didi

sh - 如何在 sh 的字符串中添加换行符?

转载 作者:行者123 更新时间:2023-12-03 04:00:43 27 4
gpt4 key购买 nike

这个

STR="Hello\nWorld"
echo $STR

作为输出产生

Hello\nWorld

而不是

Hello
World

如何在字符串中添加换行符?

注意:这个问题与echo无关。我知道echo -e,但我正在寻找一种解决方案,允许将字符串(包括换行符)作为参数传递给其他命令没有类似的选项将 \n 解释为换行符。

最佳答案

如果您使用的是 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.

关于sh - 如何在 sh 的字符串中添加换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3005963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com