替换管道字符“|” 带有转义的 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
Replace pipe character "|" with escaped pip character "\|" in string in bash script
提问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
tr
is good for one-to-one mapping of characters (read "translate").
\|
is two characters, you cannot use tr
for 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 g
flag:
此示例替换了一个|
. 如果要替换多个,请添加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 %q
modifier used by printf
will 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 f
and replaces every occurance of foo
with 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
并替换每次出现的foo
with 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="\\|"