【发布时间】:2014-03-17 15:54:44
【问题描述】:
我正在使用下面的行将 html 文件从源目录复制到目标目录。如何在将文件移动到 001.html, 002.html, 003.html 等时重命名文件?
find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)" -exec mv {} "${TargetDir}" \;
【问题讨论】:
我正在使用下面的行将 html 文件从源目录复制到目标目录。如何在将文件移动到 001.html, 002.html, 003.html 等时重命名文件?
find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)" -exec mv {} "${TargetDir}" \;
【问题讨论】:
您可以在循环中使用计数器并使用 shell 参数扩展来获取文件扩展名。
以下可能对您有用:
i=0
while read -r file; do
fn=$(printf "%03d" $((++i))) # get incremental numbers: 001, 002, ...
mv "${file}" "${TargetDir}/${fn}.${file##*.}";
done < <(find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)")
如果你的 shell 不支持进程替换,你可能会说:
i=0
for file in $(find ${SourceDir} -type f -regex ".*\.\(htm\|html\|xhtm\|xhtml\)"); do
fn=$(printf "%03d" $((++i))) # get incremental numbers: 001, 002, ...
mv "${file}" "${TargetDir}/${fn}.${file##*.}";
done
请注意,如果文件名包含奇怪字符,这可能不起作用。
【讨论】:
set +o posix 吗?