How can I use a file in a command and redirect output to the same file without truncating it?

前端 未结 14 2792
终归单人心
终归单人心 2020-11-21 22:11

Basically I want to take as input text from a file, remove a line from that file, and send the output back to the same file. Something along these lines if that makes it any

14条回答
  •  孤街浪徒
    2020-11-21 22:47

    The following will accomplish the same thing that sponge does, without requiring moreutils:

        shuf --output=file --random-source=/dev/zero 
    

    The --random-source=/dev/zero part tricks shuf into doing its thing without doing any shuffling at all, so it will buffer your input without altering it.

    However, it is true that using a temporary file is best, for performance reasons. So, here is a function that I have written that will do that for you in a generalized way:

    # Pipes a file into a command, and pipes the output of that command
    # back into the same file, ensuring that the file is not truncated.
    # Parameters:
    #    $1: the file.
    #    $2: the command. (With $3... being its arguments.)
    # See https://stackoverflow.com/a/55655338/773113
    
    function siphon
    {
        local tmp=$(mktemp)
        local file="$1"
        shift
        $* < "$file" > "$tmp"
        mv "$tmp" "$file"
    }
    

提交回复
热议问题