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

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

    The problem with the command

    sed 'code' file > file
    

    is that file is truncated by the shell before sed actually gets to process it. As a result, you get an empty file.

    The sed way to do this is to use -i to edit in place, as other answers suggested. However, this is not always what you want. -i will create a temporary file that will then be used to replace the original file. This is problematic if your original file was a link (the link will be replaced by a regular file). If you need to preserve links, you can use a temporary variable to store the output of sed before writing it back to the file, like this:

    tmp=$(sed 'code' file); echo -n "$tmp" > file
    

    Better yet, use printf instead of echo since echo is likely to process \\ as \ in some shells (e.g. dash):

    tmp=$(sed 'code' file); printf "%s" "$tmp" > file
    

提交回复
热议问题