2012-01-18 180 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