2016-08-19 97 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