Monday, September 19, 2011

Batch File Renaming in bash with Regexes/Regexps

The bash shell has a built-in POSIX regular expression matching facility. It also lets you extract parenthesized matching subexpressions within the regexp. Here's how to use it to rename a bunch of JPGs to jpegs:

for f in *.JPG; do [[ $f =~ ([^.]+)\.JPG ]] && mv $f ${BASH_REMATCH[1]}.jpeg; done

The [[ .. ]] test ensures that the rename is only executed when the file name matches the regexp. The BASH_REMATCH array is populated while the regexp match operator =~ does its job. The regular expression within the [[ .. ]] cannot be quoted, or else it won't work.

No comments:

Post a Comment