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
This produces unexpected results:
tail file.txt > file.txt && echo $(date) >> file.txt
The 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"
sponge
from the moreutils package
f=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 >>file
This 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.txt
1,-10
select all but last 10 lines
d
delete
x
save and close
tail
? Do you want to discard the earlier lines?