在sh(shell)字符串中如何换行?

87 浏览
0 Comments

在sh(shell)字符串中如何换行?

这个

STR="Hello\nWorld"
echo $STR

产生的输出是

Hello\nWorld

而不是

Hello
World

我该怎么办才能在字符串中加入换行?

注:这个问题不是关于 echo。

我知道使用 echo -e 可以实现,但是我正在寻找一种解决方案,允许传递一个包含换行的字符串作为参数传递给其他没有类似的解释 \\n 的命令。

admin 更改状态以发布 2023年5月22日
0
0 Comments

Echo已经过时了,并且存在很多问题,应该导致核心转储不少于4GB。说真的,echo的问题是Unix标准化过程中发明printf实用程序的原因,消除所有问题。

因此,要在字符串中获得换行符,有两种方法:

# 1) Literal newline in an assignment.
FOO="hello
world"
# 2) Command substitution.
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

就是这样!没有SYSV与BSD回显混乱,一切都得到了整洁的打印并完全支持C转义序列的便携式支持。请大家现在使用printf来满足所有输出需求,并且不再回头看。

0
0 Comments

如果您使用Bash,您可以在特别引号的$\'string\'中使用反斜杠转义。例如,添加\\n:\n

STR=$'Hello\nWorld'
echo "$STR" # quotes are required here!

\n打印:\n

Hello
World

\n如果您使用几乎任何其他shell,只需将换行符直接插入字符串中:\n

STR='Hello
World'

\nBash在$\'\'字符串中识别其他许多反斜杠转义序列。这里是Bash手册页面的一部分:\n

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.

0