简体   繁体   中英

Bash script for renaming files, using modular arithmetic?

I've got a series of files that are namedHHMMSSxxxxxxxxxxxxxxxx.mp3, where HH,MM, and SS are parts of a timestamp and the x's are unique per file.

The timestamp follows a 24 hour form (where 10am is 100000, 12pm is 120000, 6pm is 180000, 10pm is 220000, etc). I'd like to shift each down by 10 hours, so that 10am is 000000, 12pm is 020000, etc.

I know basic BASH commands for renaming and moving, etc, but I can't figure out how to do the modular arithmetic on the filenames.

Any help would be very much appreciated.

#!/bin/bash
for f in *.mp3
do
    printf -v newhour '%02d' $(( ( 10#${f:0:2} + 14 ) % 24 ))
    echo mv "$f" "$newhour${f:2}"
done

Remove the echo to make it functional.

Explanation:

  • printf -v newhour '%02d' - this is like sprintf() , the value is stored in the named variable
  • $(( ( 10#${f:0:2} + 14 ) % 24 )) - 10# forces the number to base 10 (eg 08 would otherwise be considered an invalid octal), ${f:0:2} extracts the first two characters (the hour), the rest does the math
  • "$newhour${f:2}" - prepend the new hour before the substring of the original name, starting at the third character

The easiest way is probably to extract the timestamp and use date to turn it into a number of seconds, do normal math on the result, then convert it back. date -d datestring + format lets you do these conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM