如何用更简洁的Shell脚本按规则批量重命名多组文件?
优化后实现脚本
#!/bin/bash # 遍历1-17对应所有文件编号 for i in {1..17}; do # 生成两位数补零的序号,匹配file01/file02的命名规则 num=$(printf "%02d" ${i}) # 按修改时间倒序取对应编号的最新文件 latest_file=$(ls -t file${num}_*.pdf 2>/dev/null | head -n1) # 无匹配文件时直接跳过当前编号 [[ -z ${latest_file} ]] && continue # 生成目标文件名前缀、最后修改日期 target_prefix=T303${i} modify_date=$(date -r "${latest_file}" +%Y%b%d) # 执行重命名 mv "${latest_file}" "${target_prefix}-${modify_date}.pdf" 2>/dev/null done
适配说明
如果是在macOS系统下运行,date命令语法略有差异,把date -r "${latest_file}" +%Y%b%d替换为以下内容即可:
date -r $(stat -f %m "${latest_file}") +%Y%b%d
优化点
- 仅需一层循环覆盖所有17个文件编号,无需重复编写冗余逻辑,后续编号范围调整只需修改循环的上下限即可
- 去掉了原脚本中不必要的grep、sed、字符串截取操作,直接通过序号拼接生成对应前缀,运行效率更高
- 新增了文件存在性判断,避免对应编号无匹配文件时抛出不必要的错误
内容的提问来源于stack exchange,提问作者simtech1
相关产品推荐
相关产品推荐

