1

I would like to use sed to replaced a string in place. I've tried two ways:

sed -i 's/string_catcher/new_string/g' <file_name>

This results in an error because it doesn't treat the argument properly. This is the source of my information.

Then, I figured I could just write to file instead:

sed 's/string_catcher/new_string/g' <file_name> > <file_name>

As a work around, I considered just writing it to a new file and copying it back to the old file by overwriting. But this won't work because the file is huge. It takes several minutes to just open in vim.

However, this results in the file just being empty. why these no work? solutions? Thanks.

I'm on OSX Darwin Kernel 14.4.

makansij
  • 9,303
  • 37
  • 105
  • 183

2 Answers2

4

The option -i has different syntax on Linux and OSX.

If you want sed to modify the original file without making a backup copy on Linux you don't provide any argument to -i:

sed -i 's/string_catcher/new_string/g'  <file_name>

On macOS you have to provide an empty string as argument to -i:

sed -i '' 's/string_catcher/new_string/g'  <file_name>
axiac
  • 68,258
  • 9
  • 99
  • 134
  • 1
    Just mark question as [duplicate](http://stackoverflow.com/questions/7573368/in-place-edits-with-sed-on-os-x) and move on. Makes no sense of answering the same question over and over again. (good answer though) – Fredrik Pihl Aug 14 '15 at 08:11
  • 3
    @FredrikPihl `Makes no sense of answering the same question over and over again`, lol have you seen this site ? – 123 Aug 14 '15 at 08:29
0

On your link you find the "work-around" for working without the -i option. You just need to use a temp file to get it working. Do not overwrite the existing file during the sed command:

sed 's/string_catcher/new_string/g' file_name > file_name_2 && mv file_name_2 file_name

When string_catcher or new_string contain special characters (or when you want to insert a shell variable), you should do more.

Walter A
  • 19,067
  • 2
  • 23
  • 43