1

I need to write a script, that would copy a directory recursively, but only copying subdirectories and files matched by a certain RegEx. For instance for a tree like this:

.
└── toCopy
    ├── A
    │   ├── 123
    │   ├── D
    │   │   └── rybka23
    │   ├── file
    │   ├── file1
    │   └── random
    ├── B
    ├── C
    │   ├── file_25
    │   └── somefile
    └── E1
        └── something

For a RegEx

.*[0-9]+

I need to get a new directory:

newDir
├── A
│   ├── 123
│   ├── D
│   │   └── rybka23
│   └── file1
├── C
│   └── file_25
└── E1

So my first thinking was something like this:

find toCopy -regex ".*[0-9]+" -exec cp -R '{}' newDir \;

But that doesn't really work, because I'm only getting the paths to the files/directories I need to copy and I have no idea how to build the tree from them. I would really appreciate any hints on how to do that.

Fassty
  • 25
  • 4

1 Answers1

1

You can do that using find command and loop through the results:

#!/usr/bin/env bash

cd toDir
while IFS= read -rd '' elem; do
   if [[ -d $elem ]]; then
      mkdir -p ../newDir/"$elem"
   else
      d="${elem%/*}"
      mkdir -p ../newDir/"$d"
      cp "$elem" ../newDir/"$d"
   fi
done < <(find . -name '*[0-9]*' -print0)

This requires bash as we are using process substitution.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Exactly what I was looking for! I was thinking about using some recursive function, but calling shell commands in awk is just gruesome. This is a really ellegant solution, thanks. – Fassty May 24 '18 at 16:38