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

这个


STR="Hello\nWorld"echo $STR

产生输出


Hello\nWorld

代替


HelloWorld

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


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



慕尼黑5688855
浏览 1037回答 3
3回答

达令说

解决方案是使用$'string',例如:$ STR=$'Hello\nWorld'$ echo "$STR"HelloWorld以下是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.

德玛西亚99

Echo是九十年代,充满了危险,它的使用应该导致核心转储不低于4GB。说真的,echo的问题是Unix标准化过程最终发明printf实用程序的原因,消除了所有问题。所以要在字符串中获取换行符:FOO="helloworld"BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deletedprintf '<%s>\n' "$FOO"printf '<%s>\n' "$BAR"那里!没有SYSV和BSD回声疯狂,一切都得到了整齐的打印和完全便携式支持C转义序列。大家请printf现在使用,永远不要回头。

绝地无双

我根据其他答案做了什么NEWLINE=$'\n'my_var="__between eggs and bacon__"echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"# which outputs:spameggs__between eggs and bacon__baconknight
打开App,查看更多内容
随时随地看视频慕课网APP