Grimlockz
Grimlockz

Reputation: 2581

Script for renaming files with logical

Someone has very kindly help get me started on a mass rename script for renaming PDF files.

As you can see I need to add a bit of logical to stop the below happening - so something like add a unique number to a duplicate file name?

rename 's/^(.{5}).*(\..*)$/$1$2/' *

rename -n 's/^(.{5}).*(\..*)$/$1$2/' *
Annexes 123114345234525.pdf renamed as Annex.pdf
Annexes 123114432452352.pdf renamed as Annex.pdf

Hope this makes sense?

Thanks

Upvotes: 1

Views: 427

Answers (3)

Spencer Rathbun
Spencer Rathbun

Reputation: 14910

As noted in my answer on your previous question:

for f in *.pdf; do 
    tmp=`echo $f | sed -r 's/^(.{5}).*(\..*)$/$1$2/'`
    mv -b ./"$f" ./"$tmp"
done

That will make backups of deleted or overwritten files. A better alternative would be this script:

#!/bin/bash
for f in $*; do
    tar -rvf /tmp/backup.tar $f
    tmp=`echo $f | sed -r 's/^(.{5}).*(\..*)$/$1$2/'`
    i=1
    while [ -e tmp ]; do
        tmp=`echo $tmp | sed "s/\./-$i/"`
        i+=1
    done
    mv -b ./"$f" ./"$tmp"
done

Run the script like this:

find . -exec thescript '{}' \;

The find command gives you lots of options for specifing which files to run on, works recursively, and passes all the filenames in to the script. The script backs all file up with tar (uncompressed) and then renames them.

This isn't the best script, since it isn't smart enough to avoid the manual loop and check for identical file names.

Upvotes: 0

kev
kev

Reputation: 161974

for i in *
do
    x=''                     # counter
    j="${i:0:2}"             # new name
    e="${i##*.}"             # ext
    while [ -e "$j$x" ]      # try to find other name
    do
        ((x++))              # inc counter
    done
    mv "$i" "$j$x"           # rename
done

before

$ ls
he.pdf  hejjj.pdf  hello.pdf  wo.pdf  workd.pdf  world.pdf

after

$ ls
he.pdf  he1.pdf  he2.pdf  wo.pdf  wo1.pdf  wo2.pdf

Upvotes: 2

l0b0
l0b0

Reputation: 58988

This should check whether there will be any duplicates:

rename -n [...] | grep -o ' renamed as .*' | sort | uniq -d

If you get any output of the form renamed as [...], then you have a collision.

Of course, this won't work in a couple corner cases - If your files contain newlines or the literal string renamed as, for example.

Upvotes: 0

Related Questions