Find and replace in file and overwrite file doesn't work, it empties the file

后端 未结 13 2366
深忆病人
深忆病人 2020-11-22 08:45

I would like to run a find and replace on an HTML file through the command line.

My command looks something like this:

sed -e s/STRING_TO_REPLACE/STR         


        
13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:25

    An alternative, useful, pattern is:

    sed -e 'script script' index.html > index.html.tmp && mv index.html.tmp index.html
    

    That has much the same effect, without using the -i option, and additionally means that, if the sed script fails for some reason, the input file isn't clobbered. Further, if the edit is successful, there's no backup file left lying around. This sort of idiom can be useful in Makefiles.

    Quite a lot of seds have the -i option, but not all of them; the posix sed is one which doesn't. If you're aiming for portability, therefore, it's best avoided.

提交回复
热议问题