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

Álvaro Pérez Soria picture Álvaro Pérez Soria · Aug 3, 2016 · Viewed 12.3k times · Source

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,

Answer

janos picture janos · Aug 3, 2016

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'