Shell-使用RegEx匹配保留树结构递归复制目录 [英] Shell - copying directories recursively with RegEx matching preserving tree structure

查看:48
本文介绍了Shell-使用RegEx匹配保留树结构递归复制目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个脚本,该脚本将递归复制目录,但仅复制与某个RegEx匹配的子目录和文件.例如,对于这样的树:

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

对于RegEx

.* [0-9] +

.*[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.

推荐答案

您可以使用 find 命令执行此操作并遍历结果:

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)

这需要 bash ,因为我们正在使用进程替换.

This requires bash as we are using process substitution.

这篇关于Shell-使用RegEx匹配保留树结构递归复制目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆