简体   繁体   English

如何使用 shell 脚本将唯一文件复制到每个目录

[英]How to copy unique files to each directory using shell scripting

I have lot of files in source directory with different name and ending with some number as suffix name.我在源目录中有很多文件,名称不同,并以一些数字作为后缀名结尾。 I need to copy all the files into 3 different directory.我需要将所有文件复制到 3 个不同的目录中。 While copying, each file should be unique to other directory.复制时,每个文件对于其他目录应该是唯一的。

Example:例子:

       Source directory 
           1) Test01.csv
           2) Test02.csv
           3) Test03.csv
           4) Nontesting01.csv
           5) Nontesting02.csv
           6) Nontesting03.csv

      Destination directory
         Directory 1 : Test01.csv
                       Nontesting01.csv
         Directory 2 : Test02.csv
                       Nontesting02.csv
         Directory 3 : Test03.csv
                       Nontesting03.csv

I have tried below code but it's copying 1 file per directory.我试过下面的代码,但它在每个目录复制 1 个文件。

       #!/bin/bash

   dest=/Users/myprofile/Testing_
   count=0
   for f in *.csv ; do (cp $f/*.csv* "${dest}"${count}/$f ) ; 
   ((count++))
   done

Could someone help how to achieve this scenario using shell scripting.有人可以帮助如何使用 shell 脚本实现这种情况。

Piggy-backing on what Jetchisel said, the code should be adapted, as a loop on patterns, to look like this:根据Jetchisel所说的内容,代码应该作为模式循环进行调整,看起来像这样:

#!/bin/bash

destPref="/Users/myprofile/Testing_"

for pattern in 01 02 03
do
    files=(*${pattern}.csv) 
    cp -v -- "${files[@]}" "${destPref}${pattern}/"
done

As a general guidance, if you start by writing the code logic作为一般指导,如果您从编写代码逻辑开始

  • in pseudo-code,在伪代码中,
  • fine-grained for each task that you are trying to accomplish,对您要完成的每项任务进行细粒度处理,
  • in the correct sequence and以正确的顺序和
  • in the correct context,在正确的上下文中,

then having that worded so that it does exactly what you want it to do... will, almost explicitly , tell you WHAT you need to code for each of those, not the HOW .然后使用该措辞,使其完全按照您的意愿执行...将几乎明确地告诉您您需要为每个代码编写什么,而不是如何编写代码。 The HOW is the nitty gritty of coding. HOW是编码的本质。

If you give that a try, the solution will almost pop out of the page at you.如果您尝试一下,解决方案几乎会从您的页面中弹出。

Good luck with your apprenticeship!祝你学业顺利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM