0

I have some BackUp-Files from machines which store their Backup in different folders. Additionally the files are not created at the same time (Machine 1: every sunday, Machine 2: every first monday of the month, etc.).

I need to keep the latest 10 files in each folder and delete all the others. Because of the different backup-intervals I can't just delete all files older than x days.

The folder-structure is like this:

./<SystemType>/<FQDN_Machine1>/backup_2015_09_08_02_00_00.zip
./<SystemType>/<FQDN_Machine2>/backup_2015_09_01_14_00_00.zip
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0
IFS='
'
for i in dir/*; do
    ls -d1t $i/* | head -n-10
done | xargs rm

List all subdirs excluding latest ten and send it by xargs to rm.

pacholik
  • 8,607
  • 9
  • 43
  • 55
  • Ok... I'm a linux noob :P when I write this into a bash-file ("filename.sh") and try to run, it states "find: paths must precede expression: %T@ %p\n"... – HuppiFluppi Sep 09 '15 at 09:02
  • Ah yes... I was some kind of stupid, sorry for that. But when I execute the find command I also get the latest files which should not be found. Maybe it is easier to find the latest 10 files in each subdirectory and then reverse that command... – HuppiFluppi Sep 09 '15 at 09:45
  • Are you sure? `head -n-10` prints all except last ten. – pacholik Sep 09 '15 at 10:46
  • It's been a while, but I'm not any step further... First I need to get all Subdirs and then all files except the latest 10 of each Subdir. I've tried to use a bash with variables ("find -type d" into VAR1 and "find $(VAR1) -type f | head -n -10"), but this wasn't successful... :( – HuppiFluppi Oct 05 '15 at 08:34
  • Oh, I totally misunderstood your question. I though you want to save ten files in total. Then it is somewhat easier. – pacholik Oct 05 '15 at 11:49
-1

This is my solution:

#!/bin/bash

cat find ./ -type f | while IFS= read -r line
do
  find "$line" -type f | head -n -10 | while read file
  do
    rm -f "$file"
  done
done
  • 1
    I tried this but got the error below: cat: invalid option -- y Try `cat --help' for more information. – Alex Jul 25 '16 at 02:37
  • I've used this answer instead: https://stackoverflow.com/questions/4447326/how-to-delete-all-files-except-the-latest-three-in-a-folder – damio Jun 21 '19 at 13:08