Problem with Bash output redirection

前端 未结 11 1918
梦毁少年i
梦毁少年i 2020-12-06 06:19

I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.

$cat file.txt |ta         


        
11条回答
  •  萌比男神i
    2020-12-06 07:13

    Before 'cat' gets executed, Bash has already opened 'file.txt' for writing, clearing out its contents.

    In general, don't write to files you're reading from in the same statement. This can be worked around by writing to a different file, as above:

    $cat file.txt | tail -1 >anotherfile.txt
    $mv anotherfile.txt file.txt
    or by using a utility like sponge from moreutils:
    $cat file.txt | tail -1 | sponge file.txt
    This works because sponge waits until its input stream has ended before opening its output file.

提交回复
热议问题