Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switch the placement of 2 strings in filename, for all files in the folder with bash

I made a mistake when scraping data, and now my files get allways sorted in the wrong order.
Order in the filename now is DD:MM:YYYY but i need it to be MM:DD:YYYY

Examples of the filenames:

07.08.2020-Cf_J-rraZD4.webm      
15.02.2020-KigC0ER_On4.webm      
22.09.2020-m3iAo8SYBko.webm.srt  
30.07.2020-8Qy94fGod_0.webm.srt
07.08.2020-Cf_J-rraZD4.webm.srt  
15.02.2020-KigC0ER_On4.webm.srt  

Is there a simple way to do this with bash?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use parameter expansion with the ${var:offset:length} syntax to extract parts of the filenames.

#! /bin/bash
for f in * ; do
    new=${f:3:3}${f:0:2}${f:5}
    if [[ -f $new ]] ; then
        echo "Can't rename $f: $new already exists!" >&2
    else
        mv "$f" "$new"
    fi
done

To just generate the new names, you can process the list of old names with sed:

sed 's/^\(..\)\.\(..\)/\2.\1/'
  • ^ matches the start of a string
  • \(..\) captures two characters, the first such group can be referenced as \1, the second one as \2.
  • \. matches a literal dot.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading