【问题标题】:How to rename all files in a folder removing everything after space character in linux?如何重命名文件夹中的所有文件,删除linux中空格字符后的所有内容?
【发布时间】:2019-03-28 00:43:01
【问题描述】:

你好,我不能很好地使用正则表达式,我整天在网上搜索。 我有一个包含许多图片的文件夹:

  • 50912000 Bicchiere.jpg
  • 50913714 Sottobottiglia Bernini.jpg

我使用的是 Mac OS X,但我也可以在 Ubuntu 上尝试,我想为 bash 制作一个脚本,以删除第一个空格后的所有字符,以获得这样的解决方案:

  • 50912000.jpg
  • 50913714.jpg

对于文件夹中的所有文件。 任何帮助表示赞赏。 问候

【问题讨论】:

    标签: regex linux bash shell batch-file


    【解决方案1】:

    使用纯 BASH:

    f='50912000 Bicchiere.jpg'
    mv "$f" "${f/ *./.}"
    

    或者使用find一次修复所有文件:

    find . -type f -name "* *" -exec bash -c 'f="$1"; s="${f/_ / }"; mv -- "$f" "${s/ *./.}"' _ '{}' \;
    

    【讨论】:

    • 太棒了!那么对于文件夹中的所有文件? FILES=/path/to/* for f in $FILES do echo "Processing $f file..." # take action on each file. $f store current file name cat $f done
    • 我刚刚编辑提供了一个查找命令,它将所有有空格的文件移动到非空格。
    • 我试过了,但也许我写错了问题。我需要删除第一个空格后的所有字符串。我得到 50912000Bicchiere.jpg
    • 1 moment :D 我正在处理一些新的原始文件
    • 完美!我能问最后一件事吗?一些结果是这样的 339005_.jpg 如何使用第二个脚本删除这个 _ for all?
    【解决方案2】:

    使用 sed,

    sed 's/ .*\./\./g'
    

    注意.*前面的空格

    【讨论】:

      【解决方案3】:

      您可以结合使用 find 和小脚本。

      prompt> find . -name "* *" -exec move_it {} \;
      mv "./50912000 Bicchiere.jpg" ./50912000
      mv "./50913714 Sottobottiglia Bernini.jpg" ./50913714
      prompt> cat move_it
      #!/bin/sh
      
      dst=`echo $1 | cut -c 1-10`
      
      # remove the echo in the line below to actually rename the file
      
      echo mv '"'$1'"' $dst
      

      【讨论】:

        【解决方案4】:

        rename

        rename 's/.*\s+//' *files
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-05
          • 2018-05-19
          • 2016-03-29
          • 2022-01-23
          • 1970-01-01
          • 2012-03-08
          • 2021-08-02
          • 1970-01-01
          相关资源
          最近更新 更多