Home > database >  Bash command to recursively find directories with the newest file older than 3 days
Bash command to recursively find directories with the newest file older than 3 days

Time:09-01

I was wondering if there was a single command which would recursively find the directories in which their newest file in older than 3 days. Other solutions seem to only print the newest file in all subdirectories, I was wondering if there was a way to do it recursively and print all the subdirectories? I tried find -newermt "aug 27, 2022" -ls but this only gets me directories that have files younger than the date specified, not the youngest for each directory.

CodePudding user response:

A long one-liner to sort files by date, get uniq directory names, list by modification keeping first

find ~/.config -type f -newermt "aug 29, 2022" -print0 | xargs -r0 ls -l --time-style= %s | sort -r -k 6 | gawk '{ print $7}' | xargs -I {} dirname {} | sort | uniq | xargs -I {} bash -c "ls -lt --time-style=full-iso {} | head -n2" | grep -v 'total '

With comments

find ~/.config -type f -newermt "aug 29, 2022" -print0 |\
xargs -r0 ls -l --time-style= %s | sort -r -k 6 |\ # newer files sorted by reverse date
gawk '{ print $7}' | xargs -I {} dirname {} |\ # get directory names
sort | uniq | \ # get uniq directory names
xargs -I {} bash -c "ls -lt --time-style=full-iso {} | head -n2" |\# list each directory by time, keep first
grep -v 'total '

CodePudding user response:

If I'm understanding the requirements correctly, would you please try:

#!/bin/bash

find dir -type d -print0 | while IFS= read -r -d "" d; do               # traverse "dir" recursively for subdirectories assigning "$d" to each directory name
    if [[ -n $(find "$d" -maxdepth 1 -type f) \
        && -z $(find "$d" -maxdepth 1 -type f -mtime -3) ]]; then       # if "$d" contains file(s) and does not contain files newer than 3 days
        echo "$d"                                                       # then print the directory name "$d"
    fi
done

A one liner version:

find dir -type d -print0 | while IFS= read -r -d "" d; do if [[ -n $(find "$d" -maxdepth 1 -type f) && -z $(find "$d" -maxdepth 1 -type f -mtime -3) ]]; then echo "$d"; fi; done

Please modify the top directory name dir according to your file location.

  • Related