Check how many minutes ago the last file created

Hi ,

I need help in getting how many minutes ago the last file, matching some pattern in file name, was created in a folder.

Thanks in advance.

Can you provide a sample of the input and the desired output...

Here it is.

sample input

FILE_PATTERN="^Test"
FOLDER="/nas/testfolder"

Output:

5

So it will search latest file starting with the name "Test" in the folder "/nas/testfolder" and will return how many minutes ago the file was created. In case it was created 5 minutes ago, then it will give output as 5.

Try this:

ls -al | awk '$NF ~ /pattern/ {print $7,$8,$9}' | sort -rM | head -1

Long list of all files in the current directory showing hidden files. Pipe to awk. If the last field (the file names) matches the pattern "pattern", print the 7th, 8th, and 9th field. Then sort by month in reverse order. Head the first thing in the list

Edit: Replace "ls -al" with "ls -al /directory/you/want" to look at files in the directory you want.

Edit 2: Sorry this doesn't quite answer your question. Let me see if I can find out how to take the difference between dates in bash...

1 Like

No Problems. Thank you for trying anyway.

find /home/user/log -type f -name "*.log" | xargs vdir --time-style="+%s" | awk -v d="$(date +%s)" '{printf "%s\t%d\n", $7, (d - $6)/60}'

You know what to change :wink:
directory & file pattern in find command

1 Like

I think I have a fix for my code above. Try this:

FOLDER="/nas/testfolder"
FILE=$(ls -alt ${FOLDER} | awk '$NF ~ /^Test/ {print $NF}' | head -1)
FILE_TIME=$(date --reference=$FOLDER/$FILE +%s)
NOW_TIME=$(date +%s) ; echo $((($NOW_TIME-$FILE_TIME)/60))

FOLDER is the folder that you want to look in.

FILE is the most recent file matching your pattern: Long list all files in FOLDER and sort by time. Pipe to awk. Print the last field with files that match the pattern "^Test". Pipe to head. Print the first entry.

FILE_TIME is the number of seconds past a universal date that I don't recall.

NOW_TIME is the number of seconds past that date until now.

Then print the difference of the two times divided by 60.

Note that my code might not work properly if no file matches the pattern.

1 Like

One problem here.. In case not matching file found, it's returning all files in all folder I guess. ( I am getting a huge list).

Try this then:

FOLDER="/nas/testfolder"
FILE=$(ls -alt ${FOLDER} | awk '$NF ~ /^Test/ {print $NF}' | head -1)
if [[ -z $FILE ]]
  echo "No file name matches your pattern in $FOLDER"
else
  FILE_TIME=$(date --reference=$FOLDER/$FILE +%s)
  NOW_TIME=$(date +%s) ; echo $((($NOW_TIME-$FILE_TIME)/60))
fi

If you get "No file name matches pattern in /nas/testfolder", then you should move on to the next directory.

1 Like