Question

I want to insert the line

text \\

into a file via sed. For one backslash to be inserted I would use three backslashes in the command. But escaping does not work for two backslashes:

sed -i 'text \\\\\\' $file

gives the following error:

sed: -e expression #1, char 57: unknown command: `
'
Was it helpful?

Solution

Do something like:

sed -i 's/OLDTEXT/text \\\\/' $file

You need 4 backslashes when trying to add 2. 3 for 1, 4 for 2 etc :)

OTHER TIPS

With an input file like this:

apple
orange
grape

You can insert text \\ in front of orange like this:

sed -i 's/^orange/text \\\\\n&/' input.txt

What this literally does is match the line starting with orange, replace the matched string with text \\ + a newline + the matched string, effectively inserting text \\ right in front of the line, that is:

apple
text \\
orange
grape

Note that it takes 4 backslashes to get 2 inserted. I don't know you meant about 3 backslashes for 1, you must be overlooking something there.

This might work for you (GNU sed):

sed -i '/PATTERN/i\text \\\\' file

This will overwrite the original file and insert text \\ before the line(s) containing the word PATTERN.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top