如何在不同路径中批量复制和重命名具有相同名称的文件?

时间:2016-04-19 08:14:26

标签: shell unix scripting file-handling

我有一组文件夹,每个文件夹里面都有几个子文件夹。在每个子文件夹中都有一个名为result.txt的文件我需要将所有result.txt复制到其他位置重命名结果文件。

文件夹:

 <?php
 //Upload Security
 $upload_security = md5($_SERVER['SERVER_ADDR']);
 $uploaddir = base64_decode( $_REQUEST['upload_path'] ) . "/";
 if( $_FILES[$upload_security] ):
 $file = $_FILES[$upload_security];
$file = $uploaddir . strtolower(str_replace('__', '_', str_replace('#', '_', str_replace(' ', '_', basename($file['name'])))));
    if (move_uploaded_file( $_FILES[$upload_security]['tmp_name'], $file)):
        if(chmod($file,0777)):
            echo "success"; 
        else:
            echo "error".$_FILES[$upload_security]['tmp_name'];
        endif;
    else:
        echo "error".$_FILES[$upload_security]['tmp_name'];
    endif;
 endif;
 ?> 

子文件夹: 在 abc1 efg1 doc2 ghih

aaa1
1.abc1.merged 2.abc1.merged 3.abc1.merged 4.abc1.merged

中的

efg1
等等 所有子文件夹都在一个不同的文件夹中包含result.txt,所有结果文件都重命名为result1.txt,result2.txt等。

我尝试将子文件夹的名称设置为shell脚本中的变量,然后循环进入子文件夹并将result.txt复制到其他路径并通过mv命令重命名。但只有结果每个子目录中的.txt文件都被复制而不是全部。

我尝试了以下命令:

1.efg1.merged
2.efg1.merged
3.efg1.merged
4.efg1.merged
5.efg1.merged
...
...

(我以前分配了变量)

cp  $folder/$subfolder/resu*txt ../tsv/$newfolder/

(我将$ tts定义为文件夹中子文件夹的数量)

这仅从每个父文件夹中的第一个子文件夹复制了result.txt。

1 个答案:

答案 0 :(得分:1)

我想说的是:

i=1
for dir in **/*;  # loop through files
do
    cp "$dir"/result.txt $your_path/result$i.txt
    ((i++))       # increment variable $i
done

语法**/*遍历所有子目录。

测试

$ mkdir a
$ cd a
$ mkdir a{1..4}
$ mkdir a{1..4}/a{1..4}
$ for f in **/*; do echo "$f --"; done

最后一个命令返回

a1/a1 --
a1/a2 --
...
a4/a4 --