0

I have tried using sed to read \. Unable to read \ and replace it with \\\\. I want to replace single \ with 4 \\\\.

2 Answers2

3

In a single quoted substitution, use 2 backslash for each literal backslash.

echo '\' | sed 's/\\/\\\\\\\\/'

In a double quoted substitution, you need 4 backslashes for each literal backslash, as the shell interprets each \\ as a backslash.

echo '\' | sed "s/\\\\/\\\\\\\\\\\\\\\\/"
choroba
  • 47,233
3
sed 's/[\]/&&&&/'

Within [...], which is an expression that matches a single character from the set within the brackets, each \ is literal, so there is no need to escape it (if you use single quotes around the expression; with double quotes, you still have to escape the backslash).

Each of the four & in the replacement string will be replaced by whatever was matched by the regular expression.

Alternatively, if [\] feels weird,

sed 's/\\/&&&&/'
Kusalananda
  • 333,661