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

后端 未结 13 2103
深忆病人
深忆病人 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

    When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

    To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

    sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html
    

    Without the .bak the command will fail on some platforms, such as Mac OSX.

提交回复
热议问题