This is one of those conceptually easy tasks that seems frequently required, and yet needs a complex incantation to accomplish. I have a series of files, and it will grow over time, and I want to clean them up, but keep the most recent N files.
After poking around the Google, I found this for deleting PATTERN, but keeping the five most recent:
ls -t1 PATTERN | tail -n +6 | xargs -r rm -r
That’s dash-t-one on the ls command. Or, in words:
- List files matching PATTERN, in descending order of modification time, in one column,
- Pass through all the trailing lines, starting with the sixth from the beginning,
- Bundle all those filenames into an “rm -r” command, but not if there are none.
That wasn’t so hard, was it??