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

3

8

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,

Catania answered 3/8, 2016 at 13:46 Comment(0)
M
22

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'
Mafaldamafeking answered 3/8, 2016 at 13:49 Comment(5)
When I'm using sed with a pattern with slashes or backslashes, I like to use _ as a delimiter: echo "text|jdbc" | sed -e 's_|_\\|_'Chiton
@JuanTomas not a bad idea, added to my postMafaldamafeking
Here tr works although 2 characters in the search.Neumann
@janos, you wrote one-to-one mapping with tr, but the link shows it works with two-to-one: tr "\n" "|" because of \nNeumann
@Neumann \n is a newline character. It's written with two characters, but really it's just one.Mafaldamafeking
A
2

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:

$ 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="text|jdbc|two"
$ echo "${f/|/\\|}"
text\|jdbc|two
$ echo "${f//|/\\|}"
text\|jdbc\|two
Arther answered 3/8, 2016 at 13:52 Comment(0)
A
1

You can try with awk:

echo "text|jdbc" | awk -F'|' '$1=$1' OFS="\\\|"
Archeology answered 3/8, 2016 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.