替换管道字符“|” 带有转义的 pip 字符“\|” 在 bash 脚本的字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38745477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:58:04  来源:igfitidea点击:

Replace pipe character "|" with escaped pip character "\|" in string in bash script

bashtr

提问by álvaro Pérez Soria

I am trying to replace a pipe character in an String with the escaped character in it:

我试图用其中的转义字符替换字符串中的管道字符:

Input: "text|jdbc"Output: "text\|jdbc"

输入:“text|jdbc”输出:“text\|jdbc”

I tried different things with tr:

我用 tr 尝试了不同的事情:

echo "text|jdbc" | tr "|" "\|"
...

But none of them worked. Any help would be appreciated. Thank you,

但他们都没有工作。任何帮助,将不胜感激。谢谢,

回答by janos

tris good for one-to-one mapping of characters (read "translate"). \|is two characters, you cannot use trfor this. You can use sed:

tr适用于字符的一对一映射(阅读“翻译”)。 \|是两个字符,不能tr用于此。您可以使用sed

echo 'text|jdbc' | sed -e 's/|/\|/'

This example replaces one |. If you want to replace multiple, add the gflag:

此示例替换了一个|. 如果要替换多个,请添加g标志:

echo 'text|jdbc' | sed -e 's/|/\|/g'

An interesting tip by @JuanTomasis to use a different separator character for better readability, for example:

@JuanTomas 的一个有趣提示是使用不同的分隔符来提高可读性,例如:

echo 'text|jdbc' | sed -e 's_|_\|_g'

回答by chepner

You can take advantage of the fact that |is a special character in bash, which means the %qmodifier used by printfwill escape it for you:

您可以利用 中的|特殊字符这一事实bash,这意味着使用的%q修饰符printf将为您转义它:

$ printf '%q\n' "text|jdbc"
text\|jdbc

A more general solution that doesn't require |to be treated specially is

不需要|特殊处理的更通用的解决方案是

$ f="text|jdbc"
$ echo "${f//|/\|}"
text\|jdbc

${f//foo/bar}expands fand replaces every occurance of foowith bar. The operator here is /; when followed by another /, it replaces all occurrences of the search pattern instead of just the first one. For example:

${f//foo/bar}扩展f并替换每次出现的foowith bar。这里的运算符是/; 当后跟 another 时/,它会替换所有出现的搜索模式,而不仅仅是第一个。例如:

$ f="text|jdbc|two"
$ echo "${f/|/\|}"
text\|jdbc|two
$ echo "${f//|/\|}"
text\|jdbc\|two

回答by sat

You can try with awk:

您可以尝试awk

echo "text|jdbc" | awk -F'|' '=' OFS="\\|"