Reputation: 7233
I have a directory with lots of files. I want to keep only the 6 newest. I guess I can look at their creation date and run rm on all those that are too old, but is the a better way for doing this? Maybe some linux command I could use?
Thanks!
:)
Upvotes: 2
Views: 643
Reputation: 4925
Here's my take on it, as a script. It does handle spaces in file names even if it is a bit of a hack.
#!/bin/bash
eval set -- $(ls -t1 | sed -e 's/.*/"&"/')
if [[ $# -gt 6 ]] ; then
shift 6
while [[ $# -gt 0 ]] ; do
echo "remove this file: $1" # rm "$1"
shift
done
fi
The second option to ls up there is a "one" for one file name per line. Doesn't actually seem to matter, though, since that appears to be the default when ls isn't feeding a tty.
Upvotes: 0
Reputation: 392863
rm -v $(ls -t mysvc-*.log | tail -n +7)
ls -t
, list sorted by timetail -n +7
, +7 here means length-7, so all but first 7 lines$()
makes a list of strings from the enclosed command outputrm
to remove the files, of course$()
splits on any white-space!Upvotes: 5