簡體   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

我有一個inotify等待腳本,每當它檢測到文件已上傳到源目錄時,該腳本便會將文件從一個位置移動到另一位置。

我面臨的挑戰是,我需要保留文件的基本名稱並將以下擴展名轉換:.JPEG,.JPG,.jpeg到.jpg,以便僅使用.jpg擴展名重命名文件。

目前我有這個:

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 ) &

因此,我需要一種方法來拆分和測試這些非標准擴展名,並使用正確的擴展名移動文件。 所有不具有這四個擴展名的文件都將照原樣移動。

謝謝!

戴夫

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

結合使用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 ) &

試試這種格式。 (更新)

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
) &

如果發現它正確,請從mv命令中刪除echo 它也適用於bash但也可以與其他shell兼容。 如果在read命令時遇到錯誤, read嘗試刪除-r選項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM