Removing files except the last 5 created
Hi all,
I'm new in linux, could someone has a script to remove all file in a directory except the last 5 created files. The below is the file name telma_1_1260.ARC telma_1_1261.ARC telma_1_1262.ARC telma_1_1263.ARC telma_1_1264.ARC telma_1_1265.ARC telma_1_1266.ARC telma_1_1267.ARC telma_1_1268.ARC telma_1_1269.ARC telma_1_1270.ARC telma_1_1271.ARC telma_1_1272.ARC telma_1_1273.ARC telma_1_1274.ARC telma_1_1275.ARC telma_1_1276.ARC telma_1_1277.ARC telma_1_1278.ARC telma_1_1279.ARC telma_1_1280.ARC telma_1_1281.ARC telma_1_1282.ARC telma_1_1283.ARC telma_1_1284.ARC telma_1_1285.ARC telma_1_1286.ARC telma_1_1287.ARC telma_1_1288.ARC telma_1_1289.ARC telma_1_1290.ARC telma_1_1291.ARC telma_1_1292.ARC telma_1_1293.ARC Any help? Regards |
Is it safe to assume that they are created in this order and there are no other files?
Code:
count=$(ls | wc -l) Code:
ls | head -$((count - 5)) Code:
ls | head -$((count - 5)) | xargs rm |
Might be an idea to use "ls -cr" in place of "ls" ...
|
***sorry***
I didn't read it well enough; you were talking about the last five items, not items modified in certain time.. How about producing a list with find (or some other tool) and sort it by creation time, then pick up last five elements and tell rm to delete them? |
It has '!' operation. But anyway you have to find fifth file from the end somehow.
|
Yes the files are created in this order and increment automatically.
Thanks |
Code:
ls -1t telma_1_*.ARC | tail --lines=+6 | while read f; do rm -f "$f"; done |
I had something similar:
Code:
[ `ls -1 | grep -c .` -gt 5 ] && rm -f $(ls -t1 | tail -n$(expr `ls -1 | grep -c .` - 5)) ta0kira |
Technically, if you have n files and remove first n-5, then you can just pretend to read task as 'remove files existing in the moment of launch (with possible delay to read list of them) except last five of them'. So it is at least safe to do.
|
Code:
rm `ls | sort | tail -6` --- rod |
Seems that this will always delete 6 files.
|
Gotta say, Yves solution looks the most elegant.
Simple, easy to understand - what's not to like. |
All times are GMT -5. The time now is 03:56 AM. |