如何从 bash 中的变量中删除文字字符串“\n”(不是换行符)?

How to remove the literal string "\n" (not newlines) from a variable in bash?

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

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

如何从 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

- 除了这个在 python

tr 实用程序只能处理单个字符,将它们从一组字符音译为另一组字符。这不是您想要的工具。

sed:

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

这里唯一值得注意的是\n\的转义。我正在使用此处字符串 (<<<"...") 将变量 var 的值提供给 sed.

的标准输入

我怀疑你在使用 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

请注意,在两个示例中,\ 在模式中转义为 \

您不需要外部工具,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.