If the usual sort order is ok (i.e. your files are named by the date), and your shell supports arrays, you can use them for this, avoiding the usual caveats about using ls
:
F=(./*.{gz,xz,ext4}) # list files
G=("${F[@]:5}") # pick all but the first five to another array
G=("${F[@]:0:${#F[@]}-5}") # or pick all but the last five
rm -- "${G[@]}" # remove them
zsh
can sort by date in itself, so this would grab the matching files to an array, sorted by modification time
F=(./*.(gz|xz|ext4)(Om))
((Om)
for newest last, (om)
for newest first.)
Process the array as above.
Of course, if you need to sort by modification date, can't use zsh
and know your filenames are nice, a simple ls -t | tail -n +6
would do.
(tail -n +6
starts printing at the sixth line, i.e. skips the first five. I had an off-by-one at this at first.)
With GNU ls, I think we could do ask it to quote the filenames to create suitable input for the shell, and then fill the array with the output:
eval "F=($(ls -t --quoting-style=shell-always ./*.{xz,gz}))"
But that requires trusting that ls
and the shell agree on how quotes are interpreted.
ls -l
doesn't sort files by modification time nor by creation time by default. – Mekeor Melire Apr 04 '17 at 13:09