Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I figured this would be easy, but I'm overlooking something simple:

I have a text file called test. It contains, for example, the string Alfred Hitchcock. I want to replace this with Alfred\ Hitchcock.

I figured this would do it:

grep -r1 ' ' /path/to/test | xargs sed -i 's/ /\ /g'

But it tells me:

sed: can't read Alfred: No such file or directory
sed: can't read Hitchcock: No such file or directory

Not quite sure what's going on. Any help would be great, thanks.

share|improve this question
It's not quite clear what you're trying to achieve with the grep command. Do you want to replace spaces in all files inside a directory? – Dennis Feb 10 '13 at 1:30
up vote 7 down vote accepted

You don't need grep at all:

sed -i 's/ /\ /g' /path/to/test

This will escape all spaces in the file. To escape only on some strings, see Guru's answer.

Now, if you want to do that on all files which contain a space character in a given directory:

grep -rl ' ' /path/to/test/dir | xargs sed -i 's/ /\ /g'

which is, now I realize, identical to your command line, except the char after -r, which should be a lowercase L.

(Note: I'm assuming GNU tools are being used.)

share|improve this answer
I'm nost sure if all sed(1) handle -i; use a temporary file if your's doesn't: sed 's/ /\\ /g' /path/to/test > tmpfile; mv tmpfile /path/to/test – vonbrand Feb 10 '13 at 1:21
Since grep's -r flag is being used in the OP, I believe GNU tools are being used. But that's a good point. – Aluísio A. S. G. Feb 10 '13 at 1:23
If you're new to sed and you use -i I would suggest doing -i.orig or something distinguishable, it makes a copy first (just in case you make a mistake in the sed command!) – nerdwaller Feb 10 '13 at 1:53

One way:

sed -i 's/Alfred Hitchcock/Alfred\\ Hitchcock/' /path/to/test
share|improve this answer

Try executing the grep command by itself to see what's happening.

It will print something like

/path/to/test/test:Alfred Hitchcock

When piping this to xargs, it will attempt to execute

sed -i 's/ /\ /g' /path/to/test/test:Alfred
sed -i 's/ /\ /g' Hitchcock
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .