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 thesource
directory and sends it to the pipe- the second
tar
reads that archive from the pipe, then - extracts it (
x
) to thedest
directory (-C dest
), - applies the
sed
commands:/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
Related videos on Youtube
Author by
Rajkeshwar Prasad
Updated on September 18, 2022Comments
-
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 originalsrc
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 almost 7 yearsso, 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 almost 7 years@Zanna yes this is what I want.
-
muru almost 7 yearsQuestions on macos should be posted on Unix & Linux or Ask Different.
-
-
Rajkeshwar Prasad almost 7 years
tar: Option --transform is not supported
facing issues in mac -
muru almost 7 yearsSorry, mac is off-topic here.
-
Rajkeshwar Prasad almost 7 yearsfolderX is not fixed in my case I want to copy all folders within source recursively and that wouldn't have fixed prefix even.