1
votes

I have an inotify wait script that will move a file from one location to another whenever it detects that a file has been uploaded to the source directory.

The challenge I am facing is that i need to retain the basename of the file and convert the following extensions: .JPEG, .JPG, .jpeg to .jpg so that the file is renamed with the .jpg extension only.

Currently I have this:

TARGET="/target"
SRC="/source"
( while [ 1 ]
    do inotifywait  -m -r -e close_write --format %f -q \
        $SRC | while read F
            do mv "$SRC/$F" $TARGET
            done
    done ) &

So I need a way to split out and test for those non standard extensions and move the file with the correct extension. All files not having those 4 extensions just get moved as is.

Thanks!

Dave

3

3 Answers

3
votes
if [[ "$F" =~ .JPEG\|jpg\|jpeg\|jpg ]];then 
   echo mv $F ${F%.*}.jpg
fi
1
votes

Using extglob option with some parameter expansion:

#! /bin/bash
shopt -s extglob
TARGET=/target
SRC=/source
( while : ; do
    inotifywait -m -r -r close_write --format %f -q \
        $SRC | while read F ; do
    basename=${F##*/}                               # Remove everything before /
    ext=${basename##*.}                             # Remove everything before .
    basename=${basename%.$ext}                      # Remove .$ext at the end
    if [[ $ext == @(JPG|JPEG|jpeg) ]] ; then        # Match any of the words
        ext=jpg
    fi
    echo mv "$F" "$TARGET/$basename.$ext"

        done
  done ) &
1
votes

Try this format. (Updated)

TARGET="/target"
SRC="/source"

(
    while :; do
        inotifywait  -m -r -e close_write --format %f -q "$SRC" | while IFS= read -r F; do
            case "$F" in
            *.jpg)
                echo mv "$SRC/$F" "$TARGET/"  ## Move as is.
                ;;
            *.[jJ][pP][eE][gG]|*.[jJ][pP][gG])
                echo mv "$SRC/$F" "$TARGET/${F%.*}.jpg"  ## Move with new proper extension.
                ;;
            esac
        done
    done
) &

Remove echo from the mv commands if you find it correct already. Also it's meant for bash but could also be compatible with other shells. If you get an error with the read command try to remove the -r option.