【问题标题】:Batch copy and rename multiple files in the same directory批量复制和重命名同一目录下的多个文件
【发布时间】:2021-12-05 20:39:51
【问题描述】:

我有 20 个文件,例如:

01a_AAA_qwe.sh
01b_AAA_asd.sh
01c_AAA_zxc.sh
01d_AAA_rty.sh
...

文件的名称格式相似。它们以 01 开头,格式为 01*AAA*.sh。

我希望复制和重命名同一目录下的文件,将数字01更改为02、03、04和05:

02a_AAA_qwe.sh
02b_AAA_asd.sh
02c_AAA_zxc.sh
02d_AAA_rty.sh
...

03a_AAA_qwe.sh
03b_AAA_asd.sh
03c_AAA_zxc.sh
03d_AAA_rty.sh
...

04a_AAA_qwe.sh
04b_AAA_asd.sh
04c_AAA_zxc.sh
04d_AAA_rty.sh
...

05a_AAA_qwe.sh
05b_AAA_asd.sh
05c_AAA_zxc.sh
05d_AAA_rty.sh
...

我希望将 01*.sh 文件中的 20 个复制到 02*.sh、03*.sh 和 04*.sh。这将使文件夹中的文件总数为 100。

我真的不知道如何才能做到这一点。我试图在 bash 脚本中使用 for 循环。但甚至不确定我应该选择什么作为 for 循环索引。

for i in {1..4}; do
   cp 0${i}*.sh 0${i+1}*.sh
done

不工作。

【问题讨论】:

  • $(i+1} 应该是 $((i+1))${} 用于变量,$(()) 用于数学表达式。

标签: linux bash copy rename batch-processing


【解决方案1】:

您不能在单个 cp 命令中执行多个副本,除非将一堆文件复制到单个目标目录。 cp 不会自动进行名称映射。通配符由 shell 扩展,命令本身看不到它们,因此它们不可能像这样进行模式匹配。

要将变量加 1,请使用$((i+1))

您可以使用 shell 子字符串扩展运算符来获取文件名前两个字符之后的部分。

for i in {1..4}; do
    for file in 0${i}*.sh; do
        fileend=${file:2}
        cp "$file" "0$((i+1))$fileend"
    done
done

【讨论】:

    【解决方案2】:

    将有很多方法可以将这个切片...

    使用for 循环、printf + 大括号扩展和xargs 的想法:

    for f in 01*.sh
    do
        printf "%s\n" {02..05} | xargs -r -I PFX cp ${f} PFX${f:2}
    done
    

    同样的事情,但将 printf 保存在前面的变量中:

    printf -v prefixes "%s\n" {02..05}
    
    for f in 01*.sh
    do
        <<< "${prefixes}" xargs -r -I PFX cp ${f} PFX${f:2}
    done
    

    使用一对for 循环的另一个想法:

    for f in 01*.sh
    do
        for i in {02..05}
        do
            cp "${f}" "${i}${f:2}"
        done
    done
    

    开始于:

    $ ls -1 0*.sh
    01a_AAA_qwe.sh
    01b_AAA_asd.sh
    01c_AAA_zxc.sh
    01d_AAA_rty.sh
    

    所有建议的代码 sn-ps 留给我们:

    $ ls -1 0*.sh
    01a_AAA_qwe.sh
    01b_AAA_asd.sh
    01c_AAA_zxc.sh
    01d_AAA_rty.sh
    
    02a_AAA_qwe.sh
    02b_AAA_asd.sh
    02c_AAA_zxc.sh
    02d_AAA_rty.sh
    
    03a_AAA_qwe.sh
    03b_AAA_asd.sh
    03c_AAA_zxc.sh
    03d_AAA_rty.sh
    
    04a_AAA_qwe.sh
    04b_AAA_asd.sh
    04c_AAA_zxc.sh
    04d_AAA_rty.sh
    
    05a_AAA_qwe.sh
    05b_AAA_asd.sh
    05c_AAA_zxc.sh
    05d_AAA_rty.sh
    

    注意:为便于阅读添加了空行

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      相关资源
      最近更新 更多