Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed search and replace creating new file

Tags:

sed

cygwin

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.

like image 836
Andrew Avatar asked Apr 04 '17 18:04

Andrew


2 Answers

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.

like image 69
Patrick Kelly Avatar answered Oct 21 '22 12:10

Patrick Kelly


just copy and do sed

# docker can not replace mount file
cp /etc/nginx/conf.d/nginx.template /etc/nginx/conf.d/nginx.conf
sed -i "s/findText/${replaceText}/g" /etc/nginx/conf.d/dboard_nginx.conf
like image 1
geosmart Avatar answered Oct 21 '22 13:10

geosmart