Bash SH 脚本 - 重命名具有特定扩展名的文件 + 移动到特定位置

Bash SH Script - Rename File with specific extension + Move to specific location

查看视觉解释和编辑

我正在尝试创建一个 bash 脚本来进行重命名+移动。

这是示例情况:

         |DOCTEMP - NameOfTheFolder---------|NameOfADocument.docx
FOLDER---|
         |DOCFINAL - OtherNameOfTheFolder---|OtherNameOfADocument.pdf
         |
         |etc.

我想做的是一个脚本:

第一部分

仅当文件有 docx, pdf, ppt 时才将其重命名为其文件夹但没有 DOCTEMP - / DOCFINAL -.

NameOfADocument.docx => NameOfTheFolder.docx

OtherNameOfADocument.pdf => OtherNameOfTheFolder.pdf

第二部分

重命名后,根据旧文件夹名称的第一部分将该文件移动到另一个文件夹。

NameOfTheFolder.docx => if **DOCTEMP** then => /ROOT/DOCTEMP/NameOfTheFolder.docx

OtherNameOfTheFolder.docx => if **DOCFINAL** then => /ROOT/DOCFINAL/OtherNameOfTheFolder.pdf

我试过使用类似的东西,但它不起作用

#!/bin/bash

cd "$ROOT/FOLDER"
# for filename in *; do
find . -type f | while IFS= read filename; do # Look for files in all ~/FOLDER sub-dirs
  case "${filename,,*}" in  # this syntax emits the value in lowercase: ${var,,*}  (bash version 4)
     *.part) : ;; # Excludes *.part files from being moved
     move.sh) : ;;
     *test*)            mv "$filename" "$ROOT/DOCTEMP/" ;; # Using move there is no need to {&& rm "$filename"}
     *) echo "Don't know where to put $filename" ;;
  esac
done

编辑:视觉解释

给出

ROOT/DOWNLOADS/OFFICE - House/file.docx
              /IWORK - Car/otherfile.docx

然后是第一部分

ROOT/DOWNLOADS/OFFICE - House/House.docx
              /IWORK - Car/Car.docx

然后是第二部分

ROOT/DOCUMENTS/OFFICE/House.docx
              /IWORK/Car.docx

docx可以是pdf或ppt;这里只是一个例子

EDIT2:最终脚本

 #!/bin/bash
shopt -s nullglob
for filename in /ROOT/DOWNLOADS/{OFFICE,IWORK}/*/*.{docx,pdf,ppt}; do
    new_path="$(dirname $filename).${filename##*.}"
    new_path="${new_path/DOWNLOADS/DOCUMENTS}"
    echo "moving $filename -> $new_path"
    mv "$filename" "$new_path" 
done

我可能错过了该解释中的一些要点。但这会如你所愿吗?

#!/bin/bash
shopt -s nullglob
for filename in /ROOT/DOWNLOADS/{OFFICE,IWORK}/*/*.{docx,pdf,ppt}; do
    new_path="$(dirname $filename).${filename##*.}"
    new_path="${new_path/DOWNLOADS/DOCUMENTS}"
    echo "moving $filename -> $new_path"
    mv "$filename" "$new_path" 
done