Any advise on how to do delete all files and only keep the latest file in each sub-directories, starting from a specific directory? This is what I have tried:
#!/bin/bash
find /home/ftp/ -type f | while IFS= read -r line
do
find "$line" -type f | head -n -1 | while read file
do
#rm -f "$file"
echo "$file"
done
done
I have 2 sub-directories in /home/ftp/upload and /home/ftp/download. Both sub-directories have 2 files in each of the sub-directories.
When tested the script above, there is no file name echo out.
find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head -n1
will list the latest file name. Use this logic to develop your script. If you fails at some point, do ask.find
should be-type d
to select the directories. Note, though, that the secondfind
doesn't order the results so you may end up keeping files at random, rather than "latest".