问题
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.
回答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.
来源:https://stackoverflow.com/questions/50513734/shell-copying-directories-recursively-with-regex-matching-preserving-tree-stru