Somenath Sinha
Somenath Sinha

Reputation: 1214

How to replace space with \(space) using 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.

Upvotes: 15

Views: 51823

Answers (2)

Daniel
Daniel

Reputation: 631

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.

Upvotes: 3

heemayl
heemayl

Reputation: 42137

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

Upvotes: 22

Related Questions