为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑5688855 2019-08-30 14:08:51
这个STR="Hello\nWorld"echo $STR产生输出Hello\nWorld代替HelloWorld如何在字符串中添加换行符?注意:这个问题不是关于回声。 我知道echo -e,但我正在寻找一种解决方案,允许将一个字符串(包括换行符)作为参数传递给其他命令,这些命令没有类似的选项来解释\n为换行符。
查看完整描述

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.


查看完整回答
反对 回复 2019-08-30
?
德玛西亚99

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现在使用,永远不要回头。


查看完整回答
反对 回复 2019-08-30
?
绝地无双

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


查看完整回答
反对 回复 2019-08-30
  • 3 回答
  • 0 关注
  • 1030 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信