Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

3 Answers 3

up vote 4 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
add comment

One way:

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

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.