chybee chybee - 5 months ago 19
Bash Question

OS X file rename

I have PDFs with the following name pattern:

ABC12345V1_6789_V0-1_xyz.pdf
ABC12345V4_6789_V3-7_xyz.pdf


Important parts are V# and V#-#. Whatever is the number after the first V the number after the second V is always one less. I'd like to create a service that renames the above pattern to these:

ABC12345V1_6789_V1_xyz.pdf
ABC12345V4_6789_V4_xyz.pdf


Basically the V#-# part needs to be identical to the first V# in the filename. There may be other letter Vs somewhere in the filename.

I found mac os x terminal batch rename useful but I'd need to assign the new value to the string to be replaced.

Answer

You could use a simple regex to accomplish this:

r=$"V([0-9])_([0-9]*)_V";

for f in *.pdf; do
    if [[ $f =~ $r ]]; then
        mv "$f" "${f/_*_/_${BASH_REMATCH[2]}_V${BASH_REMATCH[1]}_}";
    fi
done

Result:

ABC12345V1_6789_V0-1_xyz.pdf ABC12345V1_6789_V1_xyz.pdf
ABC12345V4_6789_V3-7_xyz.pdf ABC12345V4_6789_V4_xyz.pdf