0

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.

#!/bin/bash

# Array of root folders
#folders=("a" "b")
array=(httpdocs/*\/client1/backup/*.xml)

# 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
done

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))

2
  • 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. Commented May 5, 2016 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
    Commented May 7, 2016 at 2:53

1 Answer 1

0

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .