2016-08-19 95 views
0

我需要複製具有特定擴展名的文件。但問題是有多個文件具有相同的文件名。我不想覆蓋它們並存儲爲像文件_1,file_2等副本時,當我嘗試使用UNIX命令行的文件是過分的,雖然我用cp -n。 有沒有什麼辦法可以使用命令行或perl來完成這項任務? 我使用的命令是複製不覆蓋並保留擴展名的現有文件

find -L。 -name的「* .txt」 -exec CP -n {} -t〜/目的地

回答

2

您也可以使用cp --backup=numbered選項。

-1

以下perl腳本遞歸地尋找文件,並複製到目標文件夾,但如果已存在,文件重命名爲filename_1 ,filename_2

#!/usr/bin/perl 
use strict; 
use warnings; 
use File::Find; 
use File::Spec::Functions qw'catfile'; 
use File::Copy qw'move'; 
#use autodie qw'move'; 
use File::Basename; 

my ($filename);# = 'DUMBFILE'; 
my $origin  = '/home/itadmin/FoldersFind/OriginalFolder'; 
my $destination = '/home/itadmin/FoldersFind/Destination'; 

mkdir($destination, 0777); 
my ($path); 
find(\&wanted, $origin); 

sub wanted 
{ 
    if(-e $origin) 
    { 
     if($File::Find::name=~m/\.(txt|html|xml)$/gs) 
     { 
      $filename = basename($File::Find::name); 
     } 
    } 
    $path = "$destination/$filename"; 
    my $cnt; 
    while(-e $path) 
    { 
     $cnt++; 
     $path = catfile $destination, "$filename.$cnt"; 
    } 
    move($filename, $path); 
} 

輸入:(擷取文件可能是重複的)

/OriginalFolder/<folders1>/*file 
/OriginalFolder/<folders2>/*file 

輸出:(重命名)

/Destination/*file_<count> #/Destination/*file_1 
/Destination/*file_<count> #/Destination/*file_2 
+0

我知道這是爲什麼投下來? – ssr1012

1

用Perl(未經測試)

perl -MFile::Copy=cp -e '-e ($n = "~/destination/$_") or cp $_, $n for @ARGV' *.txt