2012-01-18 184 views
0

我想通过将所有出现的空格更改为下划线来重命名所有目录(递归)。例如。递归地重命名目录名称

变更前:

product images/ 
    2010 products/ 
    2011 products/ 
    2012 products/ 
misc images/ 
nav images/ 

(等)

变更后:

product_images/ 
    2010_products/ 
    2011_products/ 
    2012_products/ 
misc_images/ 
nav_images/ 

任何帮助表示赞赏。

+0

当你有 “产品图片”和“product_images”目录已经存在,那么会发生什么? – tadmc 2012-01-19 02:12:41

回答

4

看看fixnames。你会做这样的事情:一个不同的根目录,一个你不担心将其应用到你的真实目录前改写(munging),

fixdirs -x \s -r _ * 

一定要先测试了这一点。

+0

此应用程序未安装在我的机器上,也不在我的Ubuntu回购版中。 :\ – 2015-03-05 21:19:07

+0

就像我可以告诉的那样,似乎很容易从Git repo安装和使用。 – 2015-03-05 21:22:48

+0

啊,够公平的。 – 2015-03-05 23:12:43

0

它可以在一个行完成:

mv "product images" product_images && for i in product_images/**; do mv "$i" "${i// /_}"; done 
+0

我认为这不仅仅是目录。递归中的文件会发生什么,哪些文件中有空格? – 2012-01-18 22:53:56

+0

如果你打算使用'**',那么不要忘记'shopt -s globstar',因为这在Bash 4.x中没有默认设置,而且你可能知道不能使用Bash 2.x或3 .x,至少不能递归 – SiegeX 2012-01-19 01:25:29

+0

@SiegeX有趣的点但是它没有在bash中使用这个shopt 3.2.48。我甚至尝试禁用每一个shopt,它仍然工作正常。 – anubhava 2012-01-19 04:31:17

1

可以使用rename命令:如果你使用的Red Hat(或类似的分布为CentOS的

rename -v 's/ /_/g' * */* */*/* */*/*/* 

.. ),那么rename命令是不同的:

rename -v ' ' _ * */* */*/* */*/*/* 

这也将重命名文件名的空间,而不仅仅是目录。但我猜这是你想要的,不是吗?

1

使用Perl与文件::查找模块,可以实现这样的事情:

use File::Find; 

my $dirname = "../test/"; 

finddepth(sub { 
    return if /^\.{1,2}$/; # ignore '.' and '..' 
    return unless -d $File::Find::name; # check if file is directory 
    if (s/\ /_/g) {  # replace spaces in filename with underscores 
    my $new_name = $File::Find::dir.'/'.$_; # new filename with path 
    if (rename($File::Find::name => $new_name)) { 
     printf "Directory '%s' has been renamed to '%s'\n", 
      $File::Find::name, 
      $new_name; 
    } else { 
     printf "Can't rename directory '%s' to '%s'. Error[%d]: %s\n", 
      $File::Find::name, 
      $new_name, 
      $!, $!; 
    } 
    } 
}, $dirname); 

前:

% tree test 
test 
├── test 1 
├── test 2 
└── test 3 
    └── test 3 4 

后:

% tree test 
test 
├── test_1 
├── test_2 
└── test_3 
    └── test_3_4