Bash SH脚本-使用特定扩展名重命名文件+移至特定位置 [英] Bash SH Script - Rename File with specific extension + Move to specific location
问题描述
查看视觉说明并进行编辑
我正在尝试创建一个bash脚本来进行重命名和移动.
I'm trying to create a bash script to do a rename+move.
这是示例情况:
|DOCTEMP - NameOfTheFolder---------|NameOfADocument.docx
FOLDER---|
|DOCFINAL - OtherNameOfTheFolder---|OtherNameOfADocument.pdf
|
|etc.
我想要做的是一个脚本,
What I want to do is a script that:
第一部分
Part I
仅当文件具有 docx,pdf,ppt
时,才将其重命名为其文件夹,但没有 DOCTEMP-
/ DOCFINAL-
.
Only if the file has docx, pdf, ppt
then rename it as its folder but without DOCTEMP -
/ DOCFINAL -
.
NameOfADocument.docx => NameOfTheFolder.docx
OtherNameOfADocument.pdf => OtherNameOfTheFolder.pdf
第二部分
Part II
重命名后,根据旧文件夹名称的第一部分将该文件移动到另一个文件夹.
After renaming, move that file to another folder depending on the first part of the name of the old folder.
NameOfTheFolder.docx => if **DOCTEMP** then => /ROOT/DOCTEMP/NameOfTheFolder.docx
OtherNameOfTheFolder.docx => if **DOCFINAL** then => /ROOT/DOCFINAL/OtherNameOfTheFolder.pdf
我尝试使用类似的方法,但是它不起作用
I tried using something like this but it doesn't work
#!/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;这里只是一个例子
docx can be pdf or ppt; here only an example
最终脚本
#!/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
推荐答案
在该解释中我可能会遗漏一些要点.但这会做你想要的吗?
I might have missed some points in that explanation. But would this do what you want?
#!/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
这篇关于Bash SH脚本-使用特定扩展名重命名文件+移至特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!