Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace space with \(space) using sed?

Tags:

bash

shell

sed

When I use sed to replace all the spaces with X, the command works, the command being:

sed 's/ /X/g' filelist.tmp

However, when I try the same to replace all occurrences of space with \space, the code being :

sed 's/ /\ /g' filelist.tmp

It doesn't work. What am I doing wrong? Note that I'm new to shell scripting.

like image 290
Somenath Sinha Avatar asked Jan 15 '17 14:01

Somenath Sinha


2 Answers

Add another \ i.e. you need to make \ literal:

sed 's/ /\\ /g'

With only a single \ before space, the \ is escaping the following space; as the space is not a special character in replacement that needs escaping, it is being taken as is.

Example:

% sed 's/ /\\ /g' <<<'foo  bar  spam'
foo\ \ bar\ \ spam
like image 163
heemayl Avatar answered Oct 22 '22 13:10

heemayl


You should use -r argument and should fix syntax to

sed -r "s/\s/\\\s/g" filelist.tmp

You have mistake in order of escaping "\" also.

like image 41
Daniel Avatar answered Oct 22 '22 11:10

Daniel