[英]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.