Why piping to the same file doesn't work on some platforms?

后端 未结 5 1635
谎友^
谎友^ 2020-12-20 22:22

In cygwin, the following code works fine

$ cat junk
bat
bat
bat

$ cat junk | sort -k1,1 |tr \'b\' \'z\' > junk

$ cat junk
zat
zat
zat

5条回答
  •  鱼传尺愫
    2020-12-20 23:01

    Using the following simple script, you can make it work like you want to:

    $ cat junk | sort -k1,1 |tr 'b' 'z' | overwrite_file.sh junk
    

    overwrite_file.sh

    #!/usr/bin/env bash
    
    OUT=$(cat -)
    
    FILENAME="$*"
    
    echo "$OUT" | tee "$FILENAME"
    

    Note that if you don't want the updated file to be send to stdout, you can use this approach instead

    overwrite_file_no_output.sh

    #!/usr/bin/env bash
    
    OUT=$(cat -)
    
    FILENAME="$*"
    
    echo "$OUT" > "$FILENAME"
    

提交回复
热议问题