Bash: Find and replace text strings

24,830

Solution 1

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.)

Solution 2

One way:

sed -i 's/Alfred Hitchcock/Alfred\\ Hitchcock/' /path/to/test

Solution 3

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:
24,830

Related videos on Youtube

Conor Taylor
Author by

Conor Taylor

Updated on September 18, 2022

Comments

  • Conor Taylor
    Conor Taylor over 1 year

    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.

    • Dennis
      Dennis over 11 years
      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?
  • vonbrand
    vonbrand over 11 years
    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
  • Aluísio A. S. G.
    Aluísio A. S. G. over 11 years
    Since grep's -r flag is being used in the OP, I believe GNU tools are being used. But that's a good point.
  • nerdwaller
    nerdwaller over 11 years
    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!)