1

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.

Community
  • 1
  • 1
chybee
  • 13
  • 3
  • Do you have `GNU coreutils` installed? – Inian Jun 24 '16 at 10:22
  • No, I don't have yet. Searching through previous questions I was thinking maybe [Homebrew](https://github.com/Homebrew/brew) is something that can solve this? – chybee Jun 24 '16 at 10:28
  • `brew install rename` ... and `rename --help` looks promising. Given the `brew info` knowledge, "this" is the Perl-powered file rename script [...] bottled from http://plasmasturm.org/code/rename . HTH – Dilettant Jun 24 '16 at 10:41

2 Answers2

1

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
l'L'l
  • 44,951
  • 10
  • 95
  • 146
0

This script works fine on OS X without GNU coreutils.

#!/bin/bash

for f in *.pdf
do
    _fs=$(echo "$f" |grep -o "V[0-9]_")
    newfile=$(echo "$f" | awk -F"V[0-9][^_]*_" -v fs=$_fs '{print $1fs$2fs$3}')
    mv -v "$f" "$newfile"
done

Just copy the content above to rename.sh, and chmod u+x rename.sh, it will rename all your files in current directory.

$ echo $BASH_VERSION
3.2.57(1)-release

$ grep --version
grep (BSD grep) 2.5.1-FreeBSD

$ awk --version
awk version 20070501
alijandro
  • 11,627
  • 2
  • 58
  • 74
  • It's almost fine but the **V#_** is placed at the end of the filename: `ABC12345V1_6789_V0-1_xyz.pdf ABC12345V1_6789_V0-1_xyz.pdfV1_` – chybee Jun 24 '16 at 12:41