Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove old backup files

Tags:

bash

shell

# 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.

like image 546
shantanuo Avatar asked Sep 15 '09 10:09

shantanuo


2 Answers

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.

like image 196
pavium Avatar answered Oct 30 '22 14:10

pavium


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
like image 27
Hai Vu Avatar answered Oct 30 '22 15:10

Hai Vu