Recursively copy the contents of subfolders

9,501

Solution 1

You can use for

for d in /path/to/source/*; do echo mkdir /path/to/dest/"$(basename $d)" && echo cp -rvb -- /path/to/source/"$d"/src/* /path/to/dest/"$(basename $d)"; done

If you are doing this from the parent directory of source and dest, you can use relative paths:

for d in source/*; do echo mkdir dest/"$(basename $d)" && echo cp -rvb -- "$d"/src/* dest/"$(basename $d)"; done

After testing, remove echo to actually copy the files

for d in source/*; do mkdir dest/"$(basename $d)" && cp -rvb -- "$d"/src/* dest/"$(basename $d)"; done

More readable...

for d in /path/to/source/*; do 
  echo mkdir /path/to/dest/"$(basename $d)" && 
  echo cp -rvb -- /path/to/source/"$d"/src/* /path/to/dest/"$(basename $d)"
done

Solution 2

With tar:

(cd source; tar c .) | tar x --transform 's:/src::' -C dest
  • cd source; tar c . creates a tar archive of the source directory and sends it to the pipe
  • the second tar reads that archive from the pipe, then
  • extracts it (x) to the dest directory (-C dest),
  • applies the sed command s:/src:: on the resulting path (remove the first occurrence of /src in the path)

This assumes that the source directory's actual name (and those of folder1, folder2, etc.) does not contain src.

Solution 3

You just need to add -r to copy all subfolders and files, -r will do it recursively

cp -r source/folderX/src dest/folderX

Share:
9,501

Related videos on Youtube

Rajkeshwar Prasad
Author by

Rajkeshwar Prasad

Updated on September 18, 2022

Comments

  • Rajkeshwar Prasad
    Rajkeshwar Prasad almost 2 years

    I want to copy the contents of src folders to new directories at a different location that have the names of the original src directories' parent directories.

    Here is an illustration of what I am trying to achieve.

    Input

    source/folder1/src
    source/folder2/src
    source/folder3/src
    

    Output (All folders should contain the contents of src folder)

    dest/folder1
    dest/folder2
    dest/folder3
    
    • Zanna
      Zanna almost 7 years
      so, you don't want to keep the src directories as directories - you want to move their contents to their parents, and move the parents to another location?
    • Rajkeshwar Prasad
      Rajkeshwar Prasad almost 7 years
      @Zanna yes this is what I want.
    • muru
      muru almost 7 years
      Questions on macos should be posted on Unix & Linux or Ask Different.
  • Rajkeshwar Prasad
    Rajkeshwar Prasad almost 7 years
    tar: Option --transform is not supported facing issues in mac
  • muru
    muru almost 7 years
    Sorry, mac is off-topic here.
  • Rajkeshwar Prasad
    Rajkeshwar Prasad almost 7 years
    folderX is not fixed in my case I want to copy all folders within source recursively and that wouldn't have fixed prefix even.