Reputation: 111
This is the command to remove anything more than x files from within a directory
(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm
I would like to how to modify this to do the same from outside the directory using command line
Upvotes: 1
Views: 1222
Reputation: 5877
for your original line I would suggest that you can reverse the sort and use head to exclude the last lines. It then becomes:
ls -drt ~/somedir/* | head -n-5 | xargs rm
I would encourae you to investigate the find command for problems like this. You gain more control and you could handle things like ties (e.g. remove files older than the fifth oldest)
There are unanswered details like:
ls
that you want non-recursive You get the idea. The man page for find has examples but something like:
DIR=cdplatform && find $DIR -maxdepth 1 -type f ! -newer $(ls -Fdrt ${DIR}/* | grep -v "/$" | head -n-4 | tail -1) -exec rm {} \;
Upvotes: 2
Reputation: 20456
Using find to keep only the x newest files:
find /path/to/dir ! -newer $(ls -t | sed 'x!d') -exec rm {} \;
Upvotes: 2
Reputation: 4966
Try this one:
cd /path/to/dir && { (ls -t|head -n 5;ls)|sort|uniq -u|xargs rm; }
In case of non-existing directory, it will do nothing.
Upvotes: 2