While Kusalananda has answered your question about why somefile.txt
appears in the output of ls
, I'll try and address the question about how to delete all but the two most recently created files as the linked question deals with most recently modified files instead.
First, you don't have to write the output in a file. Commands can interact with each other directly, that's what pipes are for.
Here, you could do:
ls -tU | tail -n +3 | xargs echo rm -f -- # echo for dry-run
But that's flawed in the general case as tail
works on lines and xargs
works on (possibly quoted) words, and file names are not guaranteed to be either of those. They're not even guaranteed to be valid text. It would only work properly if none of the file names contain blanks, newlines, quotes, backslashes or byte sequences not forming valid characters.
If the system is FreeBSD (as your usage of -U
suggests), you could use the json
output format that is reliably parsable like:
ls --libxo=json -Ut |
perl -MJSON::PP -l0 -0777 -ne '
@files = map {$_->{name}} @{
decode_json($_)->{"file-information"}->{directory}->[0]->{entry}
};
print for @files[2..$#files]' | xargs -0 echo rm -f --
-U
where that option means unsorted in GNUls
, the OP is probably using a BSD system where-U
means to use the creation time instead of last modification time. – Stéphane Chazelas May 16 '17 at 13:48--libxo
made it to macOS? – Stéphane Chazelas May 16 '17 at 20:56