简体   繁体   English

如何移动具有(.JPEG,.JPG,.jpeg,.jpg扩展名)的单个文件,以及如何使用Linux bash将扩展名更改为.jpg

[英]How to move a single file with (.JPEG, .JPG, .jpeg, .jpg) extensions) and change the extension to .jpg with Linux bash

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. 我有一个inotify等待脚本,每当它检测到文件已上传到源目录时,该脚本便会将文件从一个位置移动到另一位置。

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. 我面临的挑战是,我需要保留文件的基本名称并将以下扩展名转换:.JPEG,.JPG,.jpeg到.jpg,以便仅使用.jpg扩展名重命名文件。

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 戴夫

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

Using extglob option with some parameter expansion: 结合使用extglob选项和一些参数扩展:

#! /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 ) &

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. 如果发现它正确,请从mv命令中删除echo Also it's meant for bash but could also be compatible with other shells. 它也适用于bash但也可以与其他shell兼容。 If you get an error with the read command try to remove the -r option. 如果在read命令时遇到错误, read尝试删除-r选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM