How can I add a backslash using sed? [duplicate]

I want to add a backslash \ printed between Hello and World in command line using sed. It should show output Hello \ World.

What do I have to do?

2

3 Answers

If you have a file named hw containing Hello World, the sed command would be:

sed 's/ / \\ /' hw

This displays the wanted result on the screen. If you want to edit the file, add -i:

sed -i 's/ / \\ /' hw

The command replaces the space by space\space. You need two \\ because \ is an escape character.

1

I used a text file containing the texts Hello World and with this sed command:

sed 's/Hello/Hello \\/' helloworld.txt

And the output is:

Hello \ World

Note: This can be used too:

sed 's/World/\\ World/' helloworld.txt

The sed command finds the Hello text and adds a \ to the front and that outputs the result seen. The \\ escapes the \ so it's seen as a real (literal) \ not a special character.

I used \ at the end of code like this:

sed -i -r "Hello \\ World \\" mytext.txt 

This resulted in Hello \ World, as desired. But thank you, all.

5

You Might Also Like