So I'm trying to move images of a specific dimension to another folder. But working with a huge number of files, the same filename once and a while presents itself. And I have been using this script:


find "$targetDir" -iname '*.jpg' -o -iname '*.png' -o -iname '*.bmp' -o -iname '*.jpeg' 2>/dev/null | \
while read -r filename; do
    hw="$(sips -g pixelHeight -g pixelWidth "$filename" 2>/dev/null)"
    h="$(awk '/pixelHeight/{print $2}'<<<"$hw")"
    w="$(awk '/pixelWidth/{print $2}'<<<"$hw")"
    if [[ $h -eq 270 ]] && [[ $w -eq 360 ]]; then
        mv "$filename" "$targetDir/hehe"

I found out that mv had a backup command mv --backup=t but that is just for linux, so I can't use that. But it would be great to have some sort of equal function in this script above.

So how can I add a incremental number if the same filename appears?

2 Answers 2


If you are already a homebrew user, you could install GNU coreutils and get quick access to GNU mv. This is installed as gmv so that it doesn't break any scripts that rely on BSD mv's syntax.

If you don't use homebrew and do not want to install it, you'll need to do tests with [ -f ${filename} ] etc. (which I expect is what you wanted).

Once you have homebrew installed, run,

brew install fileutils

Then you can gmv --backup=t as you wished to.


This isn't that difficult to do. You need to test if the file exists in the target directory then add an increment to the file name and test if that name exists.

Replace mv "$filename" "$targetDir/hehe" in your code with:

base=$filename##*/}     # same as using basename but
                        # with parameter expansion

if [ -e "${targetDir}/hehe/${base}" ]
    echo "File exists; $base needs to be renamed.."
    i=1                 # initialize the counter
    shortname=${base%.*} # file name without extension
    ext=${base##*.}     # the file extension

    while [ -e "${targetDir}/hehe/${shortname}_{$i}.${ext}" ]

    echo mv -- "$filename" "${targetDir}/hehe/${shortname}_{$i}.${ext}"

    echo "$base does not need renaming..."
    echo mv -- "$filename" "$targetDir/hehe" 

This code will only echo the mv statements and will not rename any files. Please test thoroughly. If you are confident that output will give you the desired results then remove the echo in front of the mv statements.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .