【问题标题】:Replace text in folder names替换文件夹名称中的文本
【发布时间】:2011-02-09 12:33:26
【问题描述】:

如何在 linux 中替换文件夹名称中的相同文本?

假设我有“Photos_Jun”、“Photos_July”、“Photos_Aug”等。我可以将它们重命名为“Photos Jun”、“Photos July”等的最简单方法是什么(基本上我想用下划线替换空格“”。我有大约 200 个这样的文件夹。

我正在寻找解决方案:How can I easily bulk rename files with Perl?

它看起来像我正在寻找的东西,但我不知道如何制作正则表达式来匹配字母数字后跟“_”的文件夹。

所有文件都有非数字名称,所以我认为 [a-zA-Z] 是正确的开始方式。

perl -e 'foreach $f (glob("File\\ Name*")) { $nf = $f; $nf =~ s/(\d+)$/sprintf("%03d",$1)/e; print `mv \"$f\" \"$nf\"`;}'

感谢您的帮助!

【问题讨论】:

  • 感谢所有回答的人,非 perl 解决方案最适合我。我有几个破折号要删除,当我用 - 替换 _ 时,它也很有效。

标签: regex perl search replace directory


【解决方案1】:

Linux 有一个rename 命令:

rename '-' ' ' Photos_*

【讨论】:

    【解决方案2】:

    如果您在 *nix 上并且不介意非 Perl 解决方案,这里有一个 shell (bash) 解决方案。满意后删除echo

    #!/bin/bash
    shopt -s extglob
    for file in +([a-zA-Z])*_+([a-zA-Z])/; do echo mv "$file" "${file//_/ }"; done
    

    【讨论】:

    • 小修正。如果您只想要文件夹,请在后面加上斜线。见编辑。
    【解决方案3】:
    perl -e 'use File::Copy; foreach my $f (glob("*")) { next unless -d $f; my $nf = $f; $nf =~ s/_/ /g; move($f, $nf) || die "Can not move $f to $nf\n"; }
    

    你展开单线:

    use strict; # Always do that in Perl. Keeps typoes away.
    use File::Copy; # Always use native Perl libraries instead of system calls like `mv`
    foreach my $f (glob("*")) {
        next unless -d $f; # Skip non-folders
        next unless $f =~ /^[a-z_ ]+$/i; # Reject names that aren't "a-zA-Z", _ or space
        my $new_f = $f; 
        $new_f =~ s/_/ /g; # Replace underscore with space everywhere in string
        move($f, $nf) || die "Can not move $f to $nf: $!\n";
                         # Always check return value from move, report error
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多