theDarkerHorse
theDarkerHorse

Reputation: 111

Keep x files in a directory and remove any older files

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

Answers (3)

Phil Cooper
Phil Cooper

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:

  • I assume you want to exclude subdirs in timechecks
  • I also guess from the use of ls that you want non-recursive
  • Don't know what you want do to about hidden files

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

Amit
Amit

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

Bentoy13
Bentoy13

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

Related Questions