【问题标题】:echo command not preserving \n character when storing output in a variable - bash shell script将输出存储在变量中时,echo 命令不保留 \n 字符 - bash shell 脚本
【发布时间】:2019-12-28 17:45:34
【问题描述】:

当 echo 命令将数据存储在变量中时,我正在尝试检索换行符。有人可以帮我吗

当我运行 echo -e 时,它​​会按照命令行的预期输出

bash>testfile='INFO\nERROR\nWARNING'
bash> echo -e "$testfile"`
INFO
ERROR
WARNING

但是,当我尝试将输出存储在变量中时,我缺少换行符。

bash>testoutput=`echo -e "$testfile" | grep 'WARNING\|ERROR'`
bash>echo $testoutput
ERROR WARNING

欣赏建议

【问题讨论】:

  • 在 gentoo 上为我工作。你用的是什么版本的grep? % grep --version 给grep (GNU grep) 3.1
  • 我有 grep (GNU grep) 2.20
  • 可能需要更新您的发行版。
  • 升级 grep 版本可能需要一段时间,原帖有替代解决方案吗?

标签: newline preserve


【解决方案1】:

在 unix stackexchange 上查看this answer。

看起来换行符在那里,echo 只是出于某种原因不想打印它们。请改用printf。

brundage@fatty ~ $ testfile='INFO\nERROR\nWARNING'

brundage@fatty ~ $ echo -e "$testfile"
INFO
ERROR
WARNING

brundage@fatty ~ $ testoutput=`echo -e "$testfile" | grep 'WARNING\|ERROR'`

brundage@fatty ~ $ printf "$testoutput\n"
ERROR
WARNING

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 2012-04-03
    • 2021-12-03
    • 2013-12-13
    • 2014-04-01
    • 2020-02-13
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多