Please chech my statement - delete all except file with largest number extension
Hello!
I need to remove all files except one with the greatest number suffix. I.E. I have: ... tmp.123 tmp.124 tmp.125 ... tmp.226 Now, I wrote the statement to delete all but tmp.226 -> ls -1 tmp.* |sort -t'.' -rn -k2 |sed -n '2,$p' |xargs rm -f I've tried this and it works but I need some experienced opinion... Is there any simpler solution? Many thanks!!! |
Well for a start you could squeeze a few chars out of that by using tail instead of sed (and taking ticks off around the dot in the delimiter option of sort; [EDIT] probably that "-1" for ls is not needed either):
Code:
ls tmp.* |sort -t. -rn -k2 |tail -n+2 |xargs rm -f Hopefully something better follows; I'm too tired to think of anything wise now. [EDIT] Except that you could use a time-based sorting rather than suffix-based, if you knew which file to preserve; you could touch it (thus making it the "newest" file in terms of ctime) and then remove all the "older" files: Code:
touch tmp.226 |
Sorry, I forgot to tell that is not necceserily that i.e. file tmp.223 is older ther tmp.122. So, just say that I can't rely on time of modification...
Thank you for your answer, it's really simple solution (and I like them most :))! |
All the examples you have given have three digits after the dot; will this always be true of every file that you compare?
(And note that, under Unixxy type systems that dot doesn't have a particular significance to the OS (it may have some significance to some particular app or your bash script) and temp.1234567890 is a valid filename, as is temp.123.456.789.0, temp.123.456.789.0.bak and temp.12 and so the, eg, .12 isn't an extension...the filename is the whole string of characters.) |
All times are GMT -5. The time now is 08:51 PM. |