agf1997
agf1997

Reputation: 2898

Recursivly copy directory with a specific name to new location maintaining structure

Seems like this would have been addressed somewhere previously but I can't seem to find it. Found this but --parents doesn't seem to work on MacOS.

Copying part of a directory structure to a new location

I'm trying to copy a folder of a given name and it's contents to a new location maintaining the folder structure.

Example ... copy results from src to dest

src\ --
   folder1\ --
      file1.txt
      file2.txt
      file3.txt
      results\ --
         results1.txt
         results2.txt
   folder2\ --
      file1.txt
      file2.txt
      file3.txt
      results\ --
         results1.txt
         results2.txt
   folder3\ --
      file1.txt
      file2.txt
      file3.txt
      results\ --
         results1.txt
         results2.txt

I'd like to end up with this

dest\ --
   folder1\ --
      results\ --
         results1.txt
         results2.txt
   folder2\ --
      results\ --
         results1.txt
         results2.txt
   folder3\ --
      results\ --
         results1.txt
         results2.txt

Upvotes: 2

Views: 45

Answers (2)

tshiono
tshiono

Reputation: 22012

On MacOS, which does not support --parents option of cp command, you will be able to use ditto command as an alternative.
Please try:

mkdir -p dest
cd src
find . -type d -mindepth 2 | xargs -I ditto {} ../dest

which will be equivalent to:

mkdir -p dest
cd src
find . -type d -mindepth 2 | xargs -I cp -a -P {} ../dest

if --parents or -P option is available.

Upvotes: 0

crdrisko
crdrisko

Reputation: 484

If you're in the src directory and the dest folder exists, you can run the following to recursively copy all directories and subdirectories into dest. If dest doesn't exist, create it before running the loop.

for dir in *
do   
  if [ -d $dir ]
  then    
    mkdir ../dest/$dir
    for subdir in $dir/*
    do  
      if [ -d $subdir ]
      then      
        cp -r $subdir ../dest/$subdir
      fi     
    done
  fi
done

Upvotes: 2

Related Questions