简体   繁体   中英

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. 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.

       #!/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.

Piggy-backing on what Jetchisel said, the code should be adapted, as a loop on patterns, to look like this:

#!/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.

If you give that a try, the solution will almost pop out of the page at you.

Good luck with your apprenticeship!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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