Shell - copying directories recursively with RegEx matching preserving tree structure

断了今生、忘了曾经 提交于 2021-01-28 09:14:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!