5

I found this post: Variations of sed between OSX and GNU/Linux

SED without backup file

Which provided the solution for using sed -i on Mac OSX such that it does not create a back file on a search and replace command.

E.g., Note the singlequote space singlequote after -i option to specify a zero length extension:

sed -i ' ' 's/foo/|bar/g' test.html

My problem - this DOES create a backup file for me, and it gives the backup file the same name as my input file, "test.html"

I need to run a search/replace on many files, and I don't want backup files.

Here's my actual command:

sed -i ' ' "s|research/projects/vertebrategenome/havana/|science/groups/vertebrate-annotation|g" test2.html

Where I get a backup file called "test2.html"

Community
  • 1
  • 1
Cath
  • 131
  • 1
  • 7
  • 3
    if you have a space char between the two `'` chars, remove the space and just use `-i ''` . ALSO how do you know you have a backup file, edit your Q to include output for `ls -ls firstFileInDir*` . Good luck. – shellter Nov 25 '15 at 01:18
  • @cath, mind marking the answer as accepted answer if it worked for you? Thanks – Atif May 31 '17 at 12:44
  • 1
    @atifm - thank you! I clicked the green check, I assume that is correct. – Cath Jun 01 '17 at 14:35

2 Answers2

6

On the mac, you get the BSD version of sed. It required to include a null string as an argument to -i. Note, on linux, it is happy to accept the -i with no extension.

On Linux:

sed -i 's|StringToReplace|ReplacedString|'

on MacOSX/*BSD

sed -i '' 's|StringToReplace|ReplacedString|'

Note, you want a nullstring ('') not a blank(' ').

Atif
  • 1,438
  • 16
  • 25
4

The best way I have found to have the same script work on both Linux and Mac is to:

sed -i.bak -e 's/foo/bar/' -- ${TARGET}
rm ${TARGET}.bak
vikrantt
  • 2,537
  • 1
  • 13
  • 7
  • What's the `.bak` mean on the `-i` flag? – SnazzyPencil May 19 '23 at 09:57
  • Answering my own comment above. The man-page of `sed` on MacOS doesn't do a good job of explaining it, but `sed -i` will assume that "backups" of the modified files should be created. These backups will have the same name as the original file, but with a specified extension. This extension is specified after the `-i`. If no backup file is needed, an empty string should be specified like the following: `sed -i '' -e 's/foo/bar/g' test.txt`. – SnazzyPencil May 19 '23 at 10:21