【问题标题】:bash loop to match and rename multiple files with multiple variables within the filenamesbash循环以匹配和重命名文件名中具有多个变量的多个文件
【发布时间】:2015-09-18 18:19:14
【问题描述】:

我有一个包含 500 多个文件的目录,以下是文件示例:

随机码_aa.log

随机码_aa_r-13.log

随机码_ab.log

随机码_ae.log

随机码_ag.log

随机码_ag_r-397.log

随机码_ah.log

随机码_ac.log

随机码_ac_r-41.log

random-code_ax.log

随机码_ax_r-273.log

随机码_az.log

我想做的,最好是使用 bash 循环,查看 *_r-*.log 文件的目录,如果找到,然后尝试查看是否存在类似的 .log 文件,但在 _r-*.log 之前没有任何内容,如果找到,则将 .log 文件重命名为相应的 _r-*.log 文件,但将 r 更改为 i

通过上面文件示例中的示例更好地演示:

if "random-code_aa_r-13.log" and "random-code_aa.log" exist then 
rename "random-code_aa.log" to "random-code_aa_i-13.log"

我已尝试使用 mvrename,但没有任何效果。

【问题讨论】:

    标签: bash loops rename


    【解决方案1】:

    你可以使用 sed:

    for file in *_r-*.log ; do
        barename=`echo $file | sed 's/_r-.*/.log/'`
        newname=`echo $file | sed 's/_r-\(.*\)/_i-\1/'`
    
        if [ -f $barename ] ; then
            mv $barename $newname
        fi
    done
    

    您可以尝试改进正则表达式,因为某些文件名不安全。但它应该适用于仅包含减号作为分隔符的文件名。

    【讨论】:

      【解决方案2】:

      您应该能够通过参数替换来做到这一点:

      for f in *_r-*.log
      do
          stem="${f%_r-*.log}
          num="${f%.log}"; num="${num##_r-}"
          if test -e "${stem}_aa.log"
              then mv "${stem}_aa.log" "${stem}_aa-${num}.log"
          fi
      done
      

      【讨论】:

        【解决方案3】:

        这个简单的 BASH 脚本应该可以解决这个问题:

        for f in *_r-*.log; do
           rf="${f/_r-*log/.log}"
           [[ -f "$rf" ]] && mv "$rf" "${f/_r-/_i-}"
        done
        

        【讨论】:

        • 最简单的。完美运行。
        猜你喜欢
        • 2012-02-12
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        • 2015-09-05
        • 2021-09-20
        • 2013-03-01
        • 1970-01-01
        • 2014-01-06
        相关资源
        最近更新 更多