14

Unix (and SO) newbie here trying to flex my nascent command line chops.

I'm trying to use grep and sed to scan a bunch of files in my current directory and replace all occurrences of the string "192.168.1.1" with the string "192.168.1.0" while leaving the .git folder alone.

I tried the following:

grep -lr --exclude-dir=".git" "192.168.1.1" . | xargs sed -i 's/192.168.1.1/192.168.1.0/g' 

and I get the following error:

sed: 1: "./contact.html": invalid command code .

I would really appreciate it if someone can help me figure out what's wrong with my command.

I would also be interested in learning about a more efficient way to do this task, particularly if the command is less verbose and thus easier to remember and as long as it does not involve writing a script in perl/bash/etc, but I'm currently trying to drill down sed and grep and I would still be interested in learning about why this command isn't working even if a working alternative was provided.

anubhava
  • 761,203
  • 64
  • 569
  • 643
jellycola
  • 494
  • 1
  • 5
  • 12

1 Answers1

26

Change your sed command to:

 xargs sed -i.bak 's/192\.168\.1\.1/192\.168\.1\.0/g'

sed on OSX needs a valid file extension with -i option.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • This worked, but with the annoying side effect of producing .bak files which then had to be removed. Is there any way to avoid this? – jellycola Dec 25 '13 at 16:04
  • 7
    `.bak` is not annoying but a very secure feature where you can recover original file in case something goes wrong. But if you really don't want it then use: **`xargs sed -i '' 's/192.168.1.1/192.168.1.0/g'`** – anubhava Dec 25 '13 at 17:00
  • 1
    .bak is not very useful when I'm already using version control software like git for recovery. The second one does exactly what I wanted, thanks! – jellycola Dec 26 '13 at 07:26
  • 1
    Just add ```find . -type f -name '*.bak' -delete``` – Leonardo Cardoso Sep 17 '16 at 14:19