【问题标题】:Shell move file with renaming them外壳移动文件并重命名它们
【发布时间】: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}" \;

【问题讨论】:

    标签: shell find mingw


    【解决方案1】:

    您可以在循环中使用计数器并使用 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
    

    请注意,如果文件名包含奇怪字符,这可能不起作用。

    【讨论】:

    • 谢谢。当我使用它时,我在意外标记“
    • @noway 它不保留该值,因为循环现在在子外壳中运行。你用的是哪个外壳?
    • 谢谢,我认为这是 bash。我正在使用msysgit.github.io 附带的外壳。我的脚本顶部有 #!/bin/bash。
    • @noway 检查您是否在 posix 模式下运行 bash。如果在 posix 模式下运行,bash 不支持进程替换。
    • @noway 你运行的是什么版本的 bash?您可以在运行之前尝试说set +o posix 吗?
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2014-09-26
    • 2018-10-25
    • 2020-09-15
    相关资源
    最近更新 更多