skip to Main Content

I’ve a huge amount of png files, which are named the following way: PREFIX_00000000.png

Where PREFIX_ is a fixed string and is followed by eight numbers (maybe anyday more). These numbers represent milliseconds.

Now i’m searching for a way to convert the filename from the given format to the format PREFIX_HH:mm:ss.ffff.png. (String, followed by Hour:Minute:Second.Millisecond).

The turnside? This should be done via bash (Ubuntu).

Did anyone of you do sth like this? Or does have a solution?

2

Answers


  1. Using any awk:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    shopt -s extglob
    
    while read -r old new; do
        echo mv -- "$old" "$new"
    done < <(
        printf '%sn' PREFIX_+([[:digit:]]).png |
        awk -F '[_.]' '{
            hrs  = int( ($2 / (1000 * 60 * 60)) )
            mins = int( ($2 / (1000 * 60)) % 60 )
            secs = int( ($2 / 1000) % 60 )
            ms   = $2 % 1000
            printf "%s %s_%02d:%02d:%02d.%d.%sn", $0, $1, hrs, mins, secs, ms, $3
        }'
    )
    

    $ ./tst.sh
    mv -- PREFIX_10799999.png PREFIX_02:59:59.999.png
    mv -- PREFIX_12345678.png PREFIX_03:25:45.678.png
    mv -- PREFIX_87654321.png PREFIX_24:20:54.321.png
    

    Remove the echo once you’re happy with the results.

    Check the math and tweak if necessary as I mostly just copied it from From milliseconds to hour, minutes, seconds and milliseconds.

    Login or Signup to reply.
  2. ms2hms()(
        for i; do
    
            pre=${i%_*}
    
            t=${i%.png}
            t=${t##*_}
            f=${t/${t%???}}
    
            ((
                t = t/1000,
                s = t%60,
    
                t = t/60,
                m = t%60,
    
                h = t/60
            ))
    
            printf -v o '%s_%02d:%02d:%02d.%03d.png' "$pre" $h $m $s $f
    
            echo mv -i "$i" "$o"
    
        done
    )
    

    You used "milliseconds" but gave 4 digits after the decimal. If you really intended 4 digits, replace 1000 with 10000, ??? with ????, and %03d with %04d (or append a fixed 0 if it actually is milliseconds but you still want 4 digits).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search