I am trying to replace a pipe character in an String with the escaped character in it:
Input: "text|jdbc" Output: "text\|jdbc"
I tried different things with tr:
echo "text|jdbc" | tr "|" "\\|"
...
But none of them worked. Any help would be appreciated. Thank you,
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
:
echo 'text|jdbc' | sed -e 's/|/\\|/'
This example replaces one |
. If you want to replace multiple, add the g
flag:
echo 'text|jdbc' | sed -e 's/|/\\|/g'
An interesting tip by @JuanTomas is to use a different separator character for better readability, for example:
echo 'text|jdbc' | sed -e 's_|_\\|_g'