`tail` and append in oneliner
Emily Wong
How could I tail and append a text in a file, in one line, in Bash?
My failed attempt would be
tail file.txt > file.txt && date >> file.txt 2 3 Answers
This produces unexpected results:
tail file.txt > file.txt && echo $(date) >> file.txtThe first redirection truncates the file before the tail process starts, so tail is now operating on an empty file. (ref)
2 suggestions:
a temp file:
f=file.txt tmp=$(mktemp) { tail "$f"; date; } > "$tmp" && mv "$tmp" "$f"spongefrom the moreutils packagef=file.txt { tail "$f"; date; } | sponge "$f"
Note that echo $(date) is redundant: you don't need echo to send the output of date to stdout -- date does this by default.
Another way without using temporary files or installing additional tools (but not efficient for large files):
<<<"$(<file)" tail >file && date >>fileThis reads file in a command substitution, guaranteeing that the reading of file will take place before the other redirections are resolved.
You can use Vim in Ex mode:
ex -sc '1,-10d|x' file.txt1,-10select all but last 10 linesddeletexsave and close