Search code examples
shelluniximagemagickls

How to do a loop with filenames in shellscript ordered by 'last modified'?


i'm new in Linux, and i've been trying to run a script which processes all the files in a folder using ImageMagick's convert (I rather do this task in Shell than using mogrify, because as far as I know it doesn't save different files). The files have to be processed in 'last modified' order, so I used this code:

for file in `ls -1tr {*.jpg,*.png}`; do
    # imagemagick processes with the filename...
done

This code breaks for files with spaces, and according to this answer using ls is wrong for these purposes.

I also tried this solution from this response, but apparently I got it totally wrong (It raised an 'ambiguous redirect' error) and I decided I needed help.

while read LINE; do
    ...
done `(ls -1tr {*.png,*.jpg}`

So how do I get an ordered list of filenames for a loop? (It doesn't necessarily have to be a FOR...IN loop, it can be a WHILE, or anything.)


Solution

  • try this :

    for file in `ls -1tr {*.jpg,*.png} | awk '{print $9}'`; do
        # imagemagick processes with the filename...
    done
    

    ls -lrth give's 9 coulmns in output, out of which you need only 9th column(file names), you can get that using awk

    If you have space seperated filenames, modify awk print to print all data after 9th column