sed edit file in place

前端 未结 13 1732
忘掉有多难
忘掉有多难 2020-11-22 05:20

I am trying to find out if it is possible to edit a file in a single sed command without manually streaming the edited content into a new file and

13条回答
  •  别那么骄傲
    2020-11-22 05:59

    Versions of sed that support the -i option for editing a file in place write to a temporary file and then rename the file.

    Alternatively, you can just use ed. For example, to change all occurrences of foo to bar in the file file.txt, you can do:

    echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
    

    Syntax is similar to sed, but certainly not exactly the same.

    Even if you don't have a -i supporting sed, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file, you could do inline file sed 's/foo/bar/g'. Such a script is trivial to write. For example:

    #!/bin/sh -e
    IN=$1
    shift
    trap 'rm -f $tmp' 0
    tmp=$( mktemp )
    <$IN "$@" >$tmp && cat $tmp > $IN  # preserve hard links
    

    should be adequate for most uses.

提交回复
热议问题