Take the 2-minute tour ×

What's a Unix/Linux one-liner that will let me delete all but the most recent N revisions of each file?

I've got a bunch of files with revision numbers as part of a legacy asset-management system:


I want to keep the last three of each, so in the above list the command would delete bar.r7.js, bar.r8.js and foo.r1.js.

share|improve this question
Perhaps it's time to learn how to use version control software. –  Ignacio Vazquez-Abrams Mar 31 '11 at 17:44
There's a reason I said "legacy asset-management system." Legacy as in I can't change it. –  a paid nerd Mar 31 '11 at 17:51
Have someone else change it, then. There's a limit at how much old cruft a company can use. It's for your own sanity!@ –  grawity Mar 31 '11 at 20:48
@grawity Thanks. Yes, I've got a new thing in place, but this is for cleaning up constantly-generated revision from the old thing, and I suspected that someone might enjoy the mental exercise. –  a paid nerd Mar 31 '11 at 22:47
add comment

1 Answer

up vote 1 down vote accepted
for name in foo bar; do
    printf '%s\n' "$name".r*.js | sort -V | head -n -3 | xargs -d '\n' rm -v
share|improve this answer
What if the names (foo, bar) are arbitrary? –  a paid nerd Mar 31 '11 at 20:24
@a paid nerd: Assuming the name is everything up to first .r: ls *.r* | cut -d. -f1 | sort -u | while read -r name; do –  grawity Mar 31 '11 at 20:46
Also, normally I would make sure everything in the pipeline uses null-terminated names, if it weren't for head being hardcoded to split by newline. –  grawity Mar 31 '11 at 20:48
What's sort -V ? –  a paid nerd Apr 27 '11 at 23:56
@nerd: Shorthand for sort --version-sort (which exists in latest version of GNU coreutils) –  grawity Apr 28 '11 at 4:01
add comment

Your Answer


