0

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
3
  • 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?
    – Zanna
    Aug 31, 2017 at 6:13
  • @Zanna yes this is what I want. Aug 31, 2017 at 6:23
  • 3
    Questions on macos should be posted on Unix & Linux or Ask Different.
    – muru
    Aug 31, 2017 at 6:38

3 Answers 3

5

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
4

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.

2
  • tar: Option --transform is not supported facing issues in mac Aug 31, 2017 at 6:36
  • 2
    Sorry, mac is off-topic here.
    – muru
    Aug 31, 2017 at 6:37
1

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

cp -r source/folderX/src dest/folderX

1
  • folderX is not fixed in my case I want to copy all folders within source recursively and that wouldn't have fixed prefix even. Aug 31, 2017 at 6:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.