You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历dat文件并提取分辨率执行convert命令?

提取dat文件名中的分辨率并批量执行convert命令

我有以下dat文件:

ds-1000000000000000279-1176x2184.dat
tex-1000000000000000209-2048x4096.dat
tex-1000000000000000234-1920x1280.dat
tex-1000000000000000248-688x218.dat
tex-1000000000000000278-1176x2184.dat

需要从每个文件名里提取分辨率,执行类似以下的convert命令(以第一个文件为例):

convert -size 1176x2184 -depth 32 gray:ds-1000000000000000054-1176x2184.dat ds-1000000000000000054-1176x2184.png

目前已写出基础遍历脚本:

for f in *.dat; do echo "$f"; done

但不知道如何提取分辨率。


解决方案

利用Bash的参数扩展功能即可提取分辨率,完整批量脚本如下:

for f in *.dat; do
  # 提取分辨率:截取最后一个'-'到'.dat'之间的部分
  resolution="${f##*-}"
  resolution="${resolution%.dat}"
  # 生成输出PNG文件名
  png_file="${f%.dat}.png"
  # 执行convert命令
  convert -size "$resolution" -depth 32 gray:"$f" "$png_file"
done

关键步骤解释

  • ${f##*-}:删除变量f中从开头到最后一个-的所有内容,得到分辨率.dat格式的字符串
  • ${resolution%.dat}:删除字符串末尾的.dat,得到纯净的分辨率(如1176x2184)
  • ${f%.dat}.png:将原文件名的.dat后缀替换为.png,生成输出文件路径

如果需要先验证命令是否正确,可以把convert替换为echo,预览生成的命令:

for f in *.dat; do
  resolution="${f##*-}"
  resolution="${resolution%.dat}"
  png_file="${f%.dat}.png"
  echo convert -size "$resolution" -depth 32 gray:"$f" "$png_file"
done

内容的提问来源于stack exchange,提问作者Alexey Starinsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:42:45