问题描述
我的目标是使以下过程自动化:在所有第二级子目录中搜索,并在所述子目录中查找所有名为“ Test.pptx”的文件,将其重命名为“ Test-Appended.pptx”。根据我对StackOverflow上其他问题的回答,我尝试了以下代码:
for D in *; do
if [ -d "${D}" ]; then
echo "${D}"
for E in "${D}"; do
if [ -d "${E} ]; then
echo "${E}"
for f in "Test.pptx"; do mv "$f" "Test - Appended.pptx"; done
fi
done
fi
done
我设置脚本可执行文件(使用chmod +x
)并运行它,但是出现以下错误:
line 7: unexpected EOF while looking for matching `"'
line 12: syntax error: unexpected end of file
我相对来说是Bash脚本的新手,因此,在诊断错误和实现最初目标方面的任何帮助,我将不胜感激。谢谢!
解决方法
使用find
:
while read -r pptx
do
mv -n "${pptx}" "${pptx%.pptx} - Appended.pptx"
done < <( find . -mindepth 3 -maxdepth 3 -type f -name "*.pptx" )
请注意,我没有对其进行测试,因此可能需要根据您的特殊情况进行调整。
只要在-n
中设置了mv
选项,它就不会覆盖任何内容。
真正不需要子循环。
for f in */*/Test.pptx; do mv "$f" "${f%/*}/Test - Appended.pptx"; done
${f%/*}
是当前文件的完整路径,从最后一个斜杠(/
)开始的所有内容都被去除,因此,如果文件为a/b/Test.pptx
,则${f%/*}
为{{ 1}}。