0

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

3

2 Answers 2

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/\\\\/\\\\\\\\\\\\\\\\/"
2
  • I used the sed -i 's/\\/\\\\\\\\/g' filename. It worked. Thanks. Commented Feb 1, 2022 at 8:56
  • 4
    "Thanks" on StackExchange = Upvote / Accept. Commented Feb 1, 2022 at 9:37
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/\\/&&&&/'

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.