【问题标题】:Renaming files in bash在 bash 中重命名文件
【发布时间】:2012-12-31 11:32:09
【问题描述】:

我的目录有很多文件,命名为“20130101_temp.txt”、“20130102_temp.txt”等。

如何删除所有这些文件名称中的“_temp”。即,将 20130101_temp.txt 重命名为 20130101.txt。

【问题讨论】:

    标签: bash


    【解决方案1】:

    试试这样的:

    for FILENAME in *_temp.txt; do
        mv $FILENAME `echo $FILENAME | sed -e 's/_temp//'`
    done
    

    最好先尝试一下,将mv 替换为echo

    【讨论】:

    • 注意:此解决方案依赖于 bash 之外的实用程序 -- sed。虽然大多数系统可能都有该实用程序,但并非所有系统都会。
    【解决方案2】:

    使用 bash:

    for x in *_temp.txt
    do
        mv $x ${x%%_temp.txt}.txt
    done
    

    Perl(至少在 Ubuntu 上)还有一个名为 rename 的实用程序,它采用正则表达式,因此您可以通过以下方式完成相同的操作:

    rename -n 's/_temp\.txt$/.txt/' *_temp.txt
    

    -n 选项会启动“试运行”,它只会向您显示要重命名的内容。删除它以实际执行重命名。

    【讨论】:

      【解决方案3】:

      使用带有 glob 的 for-loop 来查找文件并使用 parameter substitution 删除 _temp 以进行移动:

      for t in ????????_temp.txt; do 
          echo mv ${t} ${t/_temp/}
      done
      

      当您测试输出在您的系统上看起来正确时,删除 echo

      【讨论】:

      • 对 echo 的评论是一种很好的接触,通常你很难学会这一点
      【解决方案4】:

      这不是一个 bash 解决方案,但由于我经常遇到重命名任务,同时懒得考虑一个合理的 bash 解决方案,所以我刚刚得到了 pyRenamer,这是一个可以很好地完成类似事情的 GUI 工具。它通常可以从标准存储库安装。

      dlundquist 的解决方案效果很好。

      【讨论】:

        【解决方案5】:

        这对我有用:

        find . -depth -name '*_temp*' -execdir bash -c 'for f; do mv -i "$f" "${f//_temp/ }"; done' bash {} +
        

        【讨论】:

          猜你喜欢
          • 2020-02-18
          • 1970-01-01
          • 2012-03-25
          • 2019-09-02
          • 2014-07-17
          • 2013-03-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-01
          相关资源
          最近更新 更多