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

shantanuo
  • 31,689
  • 78
  • 245
  • 403

5 Answers5

14

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
  • 14,808
  • 4
  • 33
  • 50
4

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
  • 37,849
  • 11
  • 66
  • 93
2

See here

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

Community
  • 1
  • 1
beggs
  • 4,185
  • 2
  • 30
  • 30
1

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
  • 4,438
  • 1
  • 23
  • 26
1

Without recursive approach:

find /home/folder/ -maxdepth 1 -name "*.jpg" -mtime +2
konsolebox
  • 72,135
  • 12
  • 99
  • 105