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

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

    Warning: this is a dangerous method! It abuses the i/o buffers in linux and with specific options of buffering it manages to work on small files. It is an interesting curiosity. But don't use it for a real situation!

    Besides the -i option of sed you can use the tee utility.

    From man:

    tee - read from standard input and write to standard output and files

    So, the solution would be:

    sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee | tee index.html
    

    -- here the tee is repeated to make sure that the pipeline is buffered. Then all commands in the pipeline are blocked until they get some input to work on. Each command in the pipeline starts when the upstream commands have written 1 buffer of bytes (the size is defined somewhere) to the input of the command. So the last command tee index.html, which opens the file for writing and therefore empties it, runs after the upstream pipeline has finished and the output is in the buffer within the pipeline.

    Most likely the following won't work:

    sed s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html | tee index.html
    

    -- it will run both commands of the pipeline at the same time without any blocking. (Without blocking the pipeline should pass the bytes line by line instead of buffer by buffer. Same as when you run cat | sed s/bar/GGG/. Without blocking it's more interactive and usually pipelines of just 2 commands run without buffering and blocking. Longer pipelines are buffered.) The tee index.html will open the file for writing and it will be emptied. However, if you turn the buffering always on, the second version will work too.

提交回复
热议问题