【问题标题】:How to remove the literal string "\n" (not newlines) from a variable in bash?如何从bash中的变量中删除文字字符串“\ n”(不是换行符)?
【发布时间】:2016-11-30 16:35:50
【问题描述】:

我正在从数据库中提取一些数据,并且我要返回的字符串之一在一行中,并且包含字符串 \n 的多个实例。这些不是换行符;它们实际上是字符串\n,即反斜杠+en,或十六进制5C 6E。

我尝试使用 sed 和 tr 删除它们,但是它们似乎无法识别字符串并且根本不影响变量。这是一个很难在谷歌上搜索的问题,因为我得到的所有结果都是关于如何从字符串中删除我不需要的换行符。

如何从 bash 中的变量中删除这些字符串?

示例数据:

\n\nCreate a URL where the client can point their web browser to. This URL should test the following IP addresses and ports for connectivity.

失败命令示例:

echo "$someString" | tr '\\n' ''

操作系统:Solaris 10

Possible Duplicate - 除非这是在 python 中

【问题讨论】:

  • 你能给我们一个输入数据的例子,并告诉我们你尝试了什么吗?
  • echo "one\\ntwo" | perl -wpe 's/\\n//g'。 (输入中的\\n就是创建这样一个字符串。)

标签: bash perl awk sed tr


【解决方案1】:

我怀疑您在使用 sed 时没有正确地在替换中转义 \。另请注意,tr 不适合此任务。 最后,如果您想替换变量中的\n,那么模式替换参数扩展的一种形式)是您的最佳选择。

要替换变量中的\n,可以使用 Bash 模式替换:

$ text='hello\n\nthere\nagain'
$ echo ${text//\\n/}
hellothereagain

要替换标准输入中的\n,可以使用sed

$ echo 'hello\n\nthere\nagain' | sed -e 's/\\n//g'
hellothereagain

注意\ 在两个示例中都以\\ 形式转义。

【讨论】:

    【解决方案2】:

    tr 实用程序仅适用于单个字符,将它们从一组字符音译到另一组字符。这不是您想要的工具。

    sed:

    newvar="$( sed 's/\\n//g' <<<"$var" )"
    

    这里唯一值得注意的是\\n 中的转义。我正在使用此处字符串 (&lt;&lt;&lt;"...") 将变量 var 的值输入到 sed 的标准输入中。

    【讨论】:

      【解决方案3】:

      您不需要外部工具,bash 可以自己轻松高效地完成它:

      $ someString='\n\nCreate a URL where the client can point their web browser to.  This URL should test the following IP addresses and ports for connectivity.'
      
      $ echo "${someString//\\n/}"
      Create a URL where the client can point their web browser to.  This URL should test the following IP addresses and ports for connectivity.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-21
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 2011-05-10
        • 2018-11-20
        • 2012-06-01
        相关资源
        最近更新 更多