views:

174

answers:

4
# find /home/shantanu -name 'my_stops*' | xargs ls -lt | head -2

The command mentioned above will list the latest 2 files having my_stops in it's name. I want to keep these 2 files. But I want to delete all other files starting with "my_stops" from the current directory.

+1  A: 

See here

(ls -t|head -n 2;ls)|sort|uniq -u|xargs rm

beggs
+2  A: 

If you create backups on a regular basis, it may be useful to use the -atime option of find so only files older than your last two backups can be selected for deletion.

For daily backups you might use

$ find /home/shantanu -atime +2 -name 'my_stops*' -exec rm {} \;

but a different expression (other than -atime) may suit you better.

In the example I used +2 to mean more than 2 days.

pavium
"2" means exactly two. If you want "older than" you need to use "+2".
Dennis Williamson
Good point! yes, use +2
pavium
+1  A: 

That will show you from the second line forward ;)

find /home/shantanu -name 'my_stops*' | xargs ls -lt | tail -n +2

Just keep in mind that find is recursive ;)

Carlos Tasada
You can use `-maxdepth` to control recursion.
Dennis Williamson
A: 

Here is a non-recursive solution:

ls -t my_stops* | awk 'NR>2 {system("rm \"" $0 "\"")}'

Explanation:

  • The ls command lists files with the latest 2 on top
  • The awk command states that for those lines (NR = number of records, i.e. lines) greater than 2, delete them
  • The quote characters are needed just in case the file names have embedded spaces
Hai Vu