Rename file in Mac OS Terminal using Regex

5,726

You can try

for a in *.jpg ; do mv -- "$a" "${a:22:4}-${a:26:2}-${a:28:2} ${a:30:2}-${a:32:2}-${a:34:2}.jpg" ; done

A bit ugly, but it should get the job done. Like always, make sure to test on a copy before.

Share:
5,726

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin almost 2 years

    Hundreds of images need to be renamed with a terminal command using regex on MacOS 10.9 Mavericks.

    The files are named this way:

    0045AW489R3T(IPCAM)_0_20131124101245_931.jpg
    0021DF025C8E(IPCAM)_0_20131127101721_44591.jpg
    389223GT4Z6W(IPCAM)_0_20131128103423_7893282.jpg
    

    They need to be renamed to this:

    2013-11-24  10-12-45.jpg
    2013-11-27  10-17-21.jpg
    2013-11-28  10-34-23.jpg
    

    Can anyone please show me how to do it?

    • Admin
      Admin over 10 years
      Why do you want to use a regular expression?
    • Admin
      Admin over 10 years
      You might find the answer to this question a guide to what you want to do. stackoverflow.com/questions/13278391/…
    • Admin
      Admin over 10 years
      I just assumed that a regular expression would be the only way to do it. Now I know that I was wrong.
    • Admin
      Admin over 10 years
      Yeah, if its fixed format, probably don't need a regex. But, if badly formed filename sneaks in, a regex can give you more options for a recovery.
    • Admin
      Admin over 10 years
      Not complete, but I use something like: for a in *; do b=$(echo $a | perl -pe 's/^\d(\d\d)/\1/'); mv "$a" "$b"; done
  • Admin
    Admin over 10 years
    Are the ${a:22:4} substrings? start at character 22 and pull 4 characters?
  • damienfrancois
    damienfrancois over 10 years
    Yes they are. Assuming, as the in example, that all strings are formatted the same way.
  • Admin
    Admin over 10 years
    This works, I was able to embedd this into my Hazel.app folder action as intended. Thank you.