George V. Reilly

Bash: Bulk Renaming

I had to rename several hundred thousand files today. Thanks to a botched invocation of Im­ageMag­ick, they all looked like unique_pre­fix.png.jpg, whereas we simply wanted unique_pre­fix.jpg.

I found a suitable answer at the Unix Stack­Ex­change. As one of the many variants of parameter sub­sti­tu­tion, Bash supports ${var/Pattern/Re­place­men­t}: “first match of Pattern within var replaced with Re­place­ment.”

for f in *.png.jpg;
    mv $f "${f/.png}"

The target expression could also have been written as "${f/.png.jpg/.jpg}"

blog comments powered by Disqus
Review: Flashman's Lady » « Review: The Tailor of Panama