Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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:

bar.r7.js
bar.r8.js
bar.r9.js
bar.r10.js
bar.r11.js
foo.r1.js
foo.r2.js
foo.r3.js
foo.r4.js
...

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
1  
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

1 Answer 1

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
done
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.