我正在从数据库中提取一些数据,其中一个字符串在一行中,包含字符串n
的多个实例。这些不是换行符;它们实际上是字符串n
,即反斜杠+en或十六进制5C 6E。
我尝试过使用sed和tr来删除它们,但它们似乎无法识别字符串,也根本不会影响变量。这一直是一个很难在谷歌上搜索的问题,因为我得到的所有结果都是关于如何从字符串中删除换行符,这不是我需要的。
如何从bash中的变量中删除这些字符串?
示例数据:
nnCreate 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 中
我怀疑您只是在使用sed
时没有在替换中正确转义。还要注意,
tr
不太适合此任务。最后,如果要替换变量中的n
,则模式替换(参数扩展的一种形式)是最佳选择。
要替换变量中的n
,可以使用Bash模式替换:
$ text='hellonntherenagain'
$ echo ${text//\n/}
hellothereagain
要替换标准输入中的n
,可以使用sed
:
$ echo 'hellonntherenagain' | sed -e 's/\n//g'
hellothereagain
请注意,在两个示例中,模式中的都转义为
\
。
tr
实用程序将只处理单个字符,将它们从一组字符音译为另一组字符。这不是你想要的工具。
带sed
:
newvar="$( sed 's/\n//g' <<<"$var" )"
这里唯一值得注意的是在
n
中的逃逸。我使用此处的字符串(<<<"..."
)将变量var
的值输入到sed
的标准输入中。
您不需要外部工具,bash可以自己轻松高效地完成这项工作:
$ someString='nnCreate 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.