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

前端 未结 14 3010
终归单人心
终归单人心 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:48

    You can do that using process-substitution.

    It's a bit of a hack though as bash opens all pipes asynchronously and we have to work around that using sleep so YMMV.

    In your example:

    grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > >(sleep 1 && cat > file_name)
    
    • >(sleep 1 && cat > file_name) creates a temporary file that receives the output from grep
    • sleep 1 delays for a second to give grep time to parse the input file
    • finally cat > file_name writes the output

提交回复
热议问题