Shell script to delete all files of certain type in different folders, except 10 latest
You divide it into two parts. First, you build a directory structure, and in this case, we only need directories containing files. In the second part, we sort the newest file first and skip those with tail
.
#!/bin/bash
while IFS= read -rd ''; do
find "$REPLY" \
-maxdepth 1 -type f -name '*.txt' -printf '%T@\t%p\0' | sort -zk1rn | cut -zf2- | tail -zn +$((10+1)) | xargs -r -0 echo rm
done < <( \
find $PWD/data \
-mindepth 2 -type f -printf %h\\0 | sort -zu \
)
There is also the possibility to use globstar
with a for-loop
:
#!/bin/bash
shopt -s globstar nullglob
for a in data/*/**/; do
find "$a" \
-maxdepth 1 -type f -name '*.txt' -printf '%T@\t%p\0' | sort -zk1rn | cut -zf2- | tail -zn +$((10+1)) | xargs -r -0 echo rm
done
Lastly, we make use of an array of counters to keep track of the file count:
#!/bin/bash
find $PWD/data -mindepth 1 -type f -name '*.txt' -printf '%T@\t%p\0' \
| sort -zk1rn | cut -zf2- \
| awk -F / -vRS='\0' -vORS='\0' '{a=$0; NF=NF-1} b[$0]++ >= 10 {print a}' | xargs -r -0 echo rm