Search code examples
fileunixfeedtimestamp

Unix process file with latest timstamp


I'm making a program that will load data into table. I've already created the procedure. But I'm having a problem with handling the file, since there are multiple files in the directory with different timestamps.

I would like to ask what is the code to detect the LATEST timestamp of the feed and choose that one.

For example, the name of the feed is PRODUCTS_I03_20130429.dat where "PRODUCTS_I03" is just the name of the feed.

I just want to detect the latest feed through its timestamp.

Thank You in Advance!


Solution

  • You could something like this:

    $ latest=$(echo -e "PRODUCTS_I03_20130429.dat\nPRODUCTS_I03_20130428.dat"|sort -r -t"_" -k3|head -1)
    $ echo ${latest%_*}
    PRODUCTS_I03
    

    It will work only if there is two _ in the filename. The echo is just for test. You should replace it with the patters You want to check, like ls -1 PRODUCTS_*_*.dat.

    If the timestamp is the same as the date of the file, You could use something like this:

    $ latest=$(ls -1rt|head -1)
    $ echo ${latest%_*}
    

    or You can get the real date of the (last modification) timestamp using state -c %y $latest.