Search code examples
bashshellfor-looprsynccp

copy files based on matching folder


I have many folders, for instance let's consider two folders(folder1, folder2) and inside each folder there are sub folders of same name(a1,b1).

For example:

         folder1
              a1
              b1

         folder2
              a1
              b1

I just want to copy the content of sub folder(a1) of folder1 to sub folder(a1) of folder2, similarly sub folder(b1) of folder1 to sub folder(b1) of folder2.

I tried the script cp -a ./folder1/. ./folder2/a1 But it doesnot do the work...


Solution

  • for path in folder1/*/*; do
      echo cp -a "$path" "folder2/${path#folder1/}"
    done
    
    1. Remove echo once you are satisfied with the “suggestions”.
    2. If you have a reasonable file system, add --reflink to cp.
    3. Perhaps it’s actually rsync that you’re looking for, depending on how exactly this replication should work and what the initial state is. (Are the targets initially empty? If not, what should happen to the old content?)
    4. If you want to match names starting with . reasonably (i.e., without .. and .), you can use e.g. ?(.@([^.]|.?))* instead of * (with shopt -s extglob switched on).