LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Help needed to sort files based on timestamp in bash scripting. (https://www.linuxquestions.org/questions/programming-9/help-needed-to-sort-files-based-on-timestamp-in-bash-scripting-857617/)

maunir 01-20-2011 02:17 PM

Help needed to sort files based on timestamp in bash scripting.
 
I have already written a script in bash to find any new files that were modified within the last 10 minutes. The script is scheduled to run every 10 minutes. So after the find it runs against the database. This works great if the files are not dependent on each other. So our users have to wait for the next 10 minutes to drop a file if there is any dependency. So what they want is some kind of function that will look at time and will execute based on time-stamp for the file. For ex. if File A is dropped in this directory at 10:31 and then File B is dropped in the same location at 10:32 then they want file 10:31 to be executed first. I can't get either the sort functionality to work nor the stat command. There are no sub-directories but just files and a simple "ls -ltr" gives me everything from the parent directory. Any help would be greatly appreciated. Excerpt from my script.

while read sqllist;do
listoffiles=$(/usr/local/bin/find $sqllist -mmin -10)
for FILE in $listoffiles
do
"all the function against Database"
done
done < /usr/local/sbin/listsql.txt

some of the command I have tried so far and the sorting is not in correct order.
#sorting=`ls -1tr $FILE`
#sorting=`/usr/local/bin/stat --format=%Y --format=%n $FILE`

This is how my listing of file looks like
-rw-r--r-- 1 root root 0 Jan 20 11:40 test4.txt

gb2312 01-20-2011 02:54 PM

You can try the find command which can

* -mmin -10
select file modified within last 10min
* -printf '%T@ %p\n'
print timestamp (from epoch) and path

Like:

$ find /tmp -maxdepth 1 -type f -mmin -10 -printf '%p\n'p
1295556351.0000000000 /tmp/c
1295556345.0000000000 /tmp/a
1295556348.0000000000 /tmp/b

Then you can sort as number:

$ find /tmp -maxdepth 1 -type f -mmin -10 -printf '%T@ %p\n' | sort -n
1295556345.0000000000 /tmp/a
1295556348.0000000000 /tmp/b
1295556351.0000000000 /tmp/c

z1p 01-20-2011 03:35 PM

It seems like the problem with your sort is that you are doing it on a single file not the list of files.

So instead of

#sorting=`ls -1tr $FILE`

try the following so the list of files in a directory are sorted together

listoffiles=$(ls -1tr `/usr/local/bin/find $sqllist -mmin -10`)


though gb2312's solution may be more efficient.

maunir 01-24-2011 01:46 PM

Thanks gb. That worked perfectly.


All times are GMT -5. The time now is 11:55 PM.