本文翻译自:How can I have a newline in a string in sh?

This 这个

STR="Hello\nWorld"
echo $STR

produces as output 产生作为输出

Hello\nWorld

instead of 代替

Hello
World

What should I do to have a newline in a string? 如何在字符串中包含换行符?

Note: This question is not about echo . 注意: 此问题与echo无关。 I'm aware of echo -e , but I'm looking for a solution that allows passing a string (which includes a newline) as an argument to other commands that do not have a similar option to interpret \\n 's as newlines. 我知道echo -e ,但是我正在寻找一种解决方案,该方案允许将字符串(包括换行符)作为参数传递给其他命令,这些命令没有类似的选项来将\\n解释为换行符。


#1楼

参考:https://stackoom.com/question/CbzH/如何在sh的字符串中包含换行符


#2楼

Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Echo已经九十年代了,充满了危险,以至于使用它会导致核心转储不少于4GB。 Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf utility, doing away with all the problems. 严重的是,Echo的问题是Unix标准化过程最终发明了printf实用程序的原因,它消除了所有问题。

So to get a newline in a string: 因此,要在字符串中获取换行符:

FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

There! 那里! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. 没有SYSV vs BSD的回音疯狂,所有内容都被整齐地打印,并且完全支持C换码序列。 Everybody please use printf now and never look back. 大家请立即使用printf ,切勿回头。


#3楼

What I did based on the other answers was 我根据其他答案所做的是

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

#4楼

The problem isn't with the shell. 问题不在于外壳。 The problem is actually with the echo command itself, and the lack of double quotes around the variable interpolation. 问题实际上出在echo命令本身上,并且变量插值周围缺少双引号。 You can try using echo -e but that isn't supported on all platforms, and one of the reasons printf is now recommended for portability. 您可以尝试使用echo -e但并非所有平台都支持它,这是现在建议使用printf的原因之一,以实现可移植性。

You can also try and insert the newline directly into your shell script (if a script is what you're writing) so it looks like... 您也可以尝试将换行符直接插入到您的Shell脚本中(如果您正在编写的是脚本),这样看起来...

#!/bin/sh
echo "Hello
World"
#EOF

or equivalently 或同等

#!/bin/sh
string="Hello
World"
echo "$string"  # note double quotes!

#5楼

I find the -e flag elegant and straight forward 我发现-e标志优雅而直接

bash$ STR="Hello\nWorld"bash$ echo -e $STR
Hello
World

If the string is the output of another command, I just use quotes 如果字符串是另一个命令的输出,我只用引号

indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"

#6楼

The solution is to use $'string' , for example: 解决方案是使用$'string' ,例如:

$ STR=$'Hello\nWorld'
$ echo "$STR"
Hello
World

Here is an excerpt from the Bash manual page: 这是Bash手册页的节选:

   Words of the form $'string' are treated specially.  The word expands tostring, with backslash-escaped characters replaced as specified by  theANSI  C  standard.  Backslash escape sequences, if present, are decodedas 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  valuennn (one to three digits)\xHH   the  eight-bit  character  whose value is the hexadecimalvalue HH (one or two hex digits)\cx    a control-x characterThe expanded result is single-quoted, as if the  dollar  sign  had  notbeen present.A double-quoted string preceded by a dollar sign ($"string") will causethe string to be translated according to the current  locale.   If  thecurrent  locale  is  C  or  POSIX,  the dollar sign is ignored.  If thestring is translated and replaced, the replacement is double-quoted.

如何在sh的字符串中包含换行符?相关推荐

  1. matlab字符串中的换行符,如何在MATLAB中的子图中显示文本/字符串行?

    使用text()函数,将'Parent'属性设置为子图的句柄,即 figure; h1 = subplot(2, 1, 1); % Do some plotting on h1 h2 = subplo ...

  2. python中的换行符是哪个键_对Python字符串中的换行符和制表符介绍

    对Python字符串中的换行符和制表符介绍 有关换行的问题 首先提一个问题,如下. python程序代码如下: print("I'm Bob. What's your name?" ...

  3. python中表示换行的符号_对Python字符串中的换行符和制表符介绍

    下面为大家分享一篇对Python字符串中的换行符和制表符介绍,具有很好的参考价值,希望对大家有所帮助.一起过来看看吧 有关换行的问题 首先提一个问题,如下. python程序代码如下: print(& ...

  4. python怎么去掉换行符_python去除字符串中的换行符

    今天写这个,要用python去除字符串中的换行符并写入文件,网上查阅,就一句代码replace("\n",""),加上之后,搞了半天,还是不对. 以上是我今天遇 ...

  5. C# 字符串中去掉换行符、间隔符等特殊字符

    C# 字符串中去掉换行符.间隔符等特殊字符 1.String.Replace方法 在C#中替换字符串中的字符我们可以使用String提供的Replace方法. string s = "sds ...

  6. Java 去掉字符串中的换行符回车符等

    去掉一个字符串中的换行符.回车符等,将连续多个空格替换成一个空格 String string = "this just a test" Pattern p = Pattern.co ...

  7. python 替换换行符,python去除字符串中的换行符

    今天写这个,要用python去除字符串中的换行符并写入文件,网上查阅,就一句代码replace("\n",""),加上之后,搞了半天,还是不对. 以上是我今天遇 ...

  8. python中横向制表符_对Python字符串中的换行符和制表符介绍

    有关换行的问题 首先提一个问题,如下. python程序代码如下: print("I'm Bob. What's your name?") 上一行代码的输出如下: I'm Bob. ...

  9. python怎么去掉换行符_python怎么移除字符串中的换行符

    python移除字符串中的换行符的方法:可以使用[strip()]函数来实现,[strip()]函数在没有参数时会默认删除空白符,包括['\n'].['\r'].[ '\t']和[' ']. pyth ...

最新文章

  1. bash: dotnet: 未找到命令..._Docker 常用命令(.NET Core示例)
  2. 硅谷蓝图创始人 Patrick:数据驱动规模化增长
  3. python带格式复制excel样式和内容_使用python的xlrd,xlwt和xlutils.copy保留样式
  4. reduce 方法 (Array) (JavaScript)
  5. [html] 你有使用过time标签吗?说说它的用途有哪些?
  6. 承上 DBlink 与 SCN | 新增视图找出外部 SCN 跳变
  7. idea 跳转到行数,Intellij IDEA 一些不为人知的技巧
  8. 研发项目wbs分解简单案例_wbs分解案例
  9. mysql查看当前所在库_MySQL查看当前数据库库
  10. 12张图片html代码,利用JS实现多张图片合成一张图片代码
  11. linux第一周总结
  12. mysql neq_neq、eq的用法,thinkphp框架下的
  13. git的一套全流程上手(不包括报错(我忘了有哪些报错了)以及其解决方案(篇幅问题))...
  14. 数据藏在json文件中,如何爬取---以王者荣耀官网为例
  15. C++表白代码(较差)
  16. plt.imshow()中cmap参数控制颜色展示
  17. 800字让你搞懂:掩码,反掩码,通配符。
  18. charge animation 充电管理u-boot(rk817)详解
  19. bilibili怎么用用户名登录_bilibili如何激活账号 哔哩哔哩激活账号的教程
  20. 基于SSM框架的健身房会员系统

热门文章

  1. POJ3641 UVA11287 HDU1905 Pseudoprime numbers【素数判定+快速模幂】
  2. Datadog Agent是啥?它消耗什么资源?
  3. 从单机到集群会话的管理之集群模式一
  4. 关于解决error A2004: symbol type conflict错误
  5. Exchange 2010安装各角色先决条件的Powershell
  6. 学习http only cookie以及javascript创建cookie的方式
  7. idea无法正常使用SVN的解决方法
  8. 信息系统项目管理师(高级)考试大纲
  9. (亲测无坑)Centos7.x使用kubeadm安装K8s集群1.15.0版本
  10. 解决win7检测不到第二个显示器的方法