Can someone point out where am going wrong please. Am doing a directory search (Based on the folder structure and file type) The folder structure is the same for every customer. Just the customer folder is named differently. Example of structure:

  • Httpdocs/client1/channel1/backup
  • Httpdocs/client5/channel5/backup
  • Httpdocs/client8/channel1/backup

This partially works, It just shows me ALL files in the backup folder apposed to the most recent file.


# Array of root folders
#folders=("a" "b")

# Search all specified root folders
for dir in "${array[@]}"; 
do echo "$dir";
    # date of each file with "stat"
    find -path $array -type f -exec stat -f "%m,%N" {} ';' | \
        # sort by date, most recent first
        sort -gr | \
        # extract first (most recent) file
        head -1 | \
        # return file name only
        cut -d, -f2

head appears to not be working. Any reason why? is my formatting wrong?

i also tried:

find -path "*\/chanel1/backup/*.xml" -type f | sort -gr | head -1 | cut -d, -f2

This just outputs the Last folder in the list with the latest file in that folder. (I have to run this within Web Root (Httpdocs))

  • I was able to get this working with the following find -path "*/chanel1/backup/*.xml" -printf '%T+ %p\n' | sort -r | head' But there is some folders missing in the list. – Dave Hamilton May 5 '16 at 13:07
  • Something like find -type f -path "*/chanel1/backup/*.xml" -printf '%T@ %p\n' | sort -nr | head -n 1 | cut -d ' ' -f2- – user60101 May 7 '16 at 2:53

I'd use something more like your last approach, such as

for d in $(find httpdocs -type d -name backup) do ls -t $d | grep '.xml$' | head -1 done

ls -t sorts by modified time, most recent first.

If you want the full pathname in the output, you can use ls -t $d/*.xml and skip the grep. There are simple but non-obvious ways to shorten the pathname if you wish, like sed or dirname.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.