2

My set of files are named according to GMT time zone. I successfully renamed and converted all files into the required time zone using the following steps.

1. This code removes all file extensions that are .gif rename "s/.gif//g" *

2. This code converts and renames all files for f in *; do mv -v -- "$f" "$(date -d "$f" '+%Y%m%d%H%M')"; done

  • Example conversion: ‘15Z29Aug2017’ -> ‘201708292030’

Unfortunately I have to set the extension .gif once again to all files using for f in *; do mv "$f" "$f.gif"; done

How exactly can I skip the file extension removal by editing my code in step 2 ?

Step 2 taken from: How can I batch convert folder names from one date format to another

1 Answer 1

4

All you need is to strip .gif from $f and put it back on:

for f in *; do mv -v -- "$f" "$(date -d "${f%%.gif}" '+%Y%m%d%H%M')".gif; done

${f%%.gif} takes variable f and removes the last (hence # two times) occurence of .gif in it, so even a strange filename like 1.gif2.gif would only get his last .gif removed. This amazing feature is called Bash Parameter Expansion and when you search it by this name you can read all about its dazzling power, e. g. on this Bash FAQ – it's capable of so much more!

2
  • Oh so simple!!! I'm embarrassed. Where can I find a document that teaches me these tricks?
    – csheth
    Aug 29, 2017 at 18:08
  • 1
    @ChintanSheth You have to promise to me to just use bash's superpower for good. ;-) I edited it in.
    – dessert
    Aug 29, 2017 at 18:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .