Search code examples
sedcygwin

sed search and replace creating new file


I'm trying to search and replace some text within a file. I'd be fine with either creating a new file, or overwriting the existing file.

If I use

sed -i 's/<texttoreplace>/<newtext>/g' foo.txt

I end up with two files:

foo.txt is the modified file

foo.txte is the original

If I use

 sed -i 's/<texttoreplace>/<newtext>/g' foo.txt > bar.txt

I end up with 2 files:

foo.txt is the original unmodified file.

bar.txt is 0 bytes.

What am I doing wrong? I'd really prefer to just overwrite the original file in place, which certainly seems like it should be possible.


Solution

  • To make your second example work, where you explicitly want to create a second file, simply drop the -i flag.

    sed 's/<texttoreplace>/<newtext>/g' foo.txt > bar.txt
    

    Your first example is a bit of a head-scratcher. The -i flag performs the editing in place, with an optional backup file of the original contents. It works fine for me, without the creation of a '.txte' file. You might get it to work by explicitly telling it no extension, using the syntax below:

    sed -i'' 's/<texttoreplace>/<newtext>/g' foo.txt
    

    You shouldn't have to do that, but maybe there is something in your environment different from mine.