Search code examples
macosbashunixscriptingfile-rename

Way to move files in bash and rename copied file automatically without overwriting an existing file


I'm doing some major restructuring of large numbers of directories with tons of jpgs, some of which my have the same name as files in other directories. I want to move / copy files to alternate directories and have bash automatically rename them if the name matches another file in that directory (renaming IMG_238.jpg to IMG_238_COPY1.jpg, IMG_238_COPY2.jpg, etc), instead of overwriting the existing file.

I've set up a script that takes jpegs and moves them to a new directory based on exif data. The final line of the script that moves one jpg is: mv -n "$JPEGFILE" "$DIRNAME"

I'm using the -n option because I don't want to overwrite files, but now I have to go and manually sort through the ones that didn't get moved / copied. My GUI does this automatically... Is there a relatively simple way to do this in bash?

(In case it matters, I'm using bash 3.2 in Mac OSX Lion).


Solution

  • This ought to do it

    # strip path, if any
    fname="${JPEGFILE##*/}"
    [ -f "$DIRNAME/$fname" ] && {
        n=1
        while [ -f "$DIRNAME/${fname%.*}_COPY${n}.${fname##*.}" ] ; do
            let n+=1
        done
        mv "$JPEGFILE" "$DIRNAME/${fname%.*}_COPY${n}.${fname##*.}"
    } || mv "$JPEGFILE" "$DIRNAME"
    

    EDIT: Improved.