【问题标题】:How to move a single file with (.JPEG, .JPG, .jpeg, .jpg) extensions) and change the extension to .jpg with Linux bash如何使用(.JPEG、.JPG、.jpeg、.jpg)扩展名移动单个文件)并使用 Linux bash 将扩展名更改为 .jpg
【发布时间】:2013-08-17 02:13:56
【问题描述】:

我有一个 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 ) &

所以我需要一种方法来拆分和测试那些非标准扩展名并移动具有正确扩展名的文件。所有没有这 4 个扩展名的文件都会按原样移动。

谢谢!

戴夫

【问题讨论】:

    标签: linux bash file-extension file-rename


    【解决方案1】:
    if [[ "$F" =~ .JPEG\|jpg\|jpeg\|jpg ]];then 
       echo mv $F ${F%.*}.jpg
    fi
    

    【讨论】:

      【解决方案2】:

      使用带有一些参数扩展的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 ) &
      

      【讨论】:

        【解决方案3】:

        试试这种格式。 (更新)

        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,但也可以与其他外壳兼容。如果read 命令出错,请尝试删除-r 选项。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多