0

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.

4
  • Perhaps it's time to learn how to use version control software. Mar 31, 2011 at 17:44
  • 1
    There's a reason I said "legacy asset-management system." Legacy as in I can't change it. Mar 31, 2011 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!@ Mar 31, 2011 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. Mar 31, 2011 at 22:47

1 Answer 1

1
for name in foo bar; do
    printf '%s\n' "$name".r*.js | sort -V | head -n -3 | xargs -d '\n' rm -v
done
5
  • 1
    What if the names (foo, bar) are arbitrary? Mar 31, 2011 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 Mar 31, 2011 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. Mar 31, 2011 at 20:48
  • What's sort -V ? Apr 27, 2011 at 23:56
  • @nerd: Shorthand for sort --version-sort (which exists in latest version of GNU coreutils) Apr 28, 2011 at 4:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .