Bash 复制所有内容与模式匹配的目录

Bash copy all directory with content that matches a pattern

有没有什么方法可以使用 bash 脚本复制包含内容的目录。例如

// Suppose there are many directory inside Test in c as,
   /media/test/
        -- en_US
                -- file1
                -- file 2 
        -- de_DE 
               -- file 1
               -- SUB-dir1
                  -- sub file 1
               -- file 2
               .....
               .....
        -- Test 1
              --  testfile1
              -- folder
                   --- more 1  
         ............

NoW i want to copy all the directories (including sub-directory and files)
to another location which matches the pattern.
--> for example , in above case I want the directories en_US and de_DE to be copied in another
location including sub-directories and files. 

到目前为止我已经完成/发现:

1) 需要的模式为,/b/w{2}_/w{2}/b

2) 我可以列出所有目录,

$MYDIR="/media/test/"
DIRS=`ls -l $MYDIR | egrep '^d' | awk '{print }'`
for DIR in $DIRS
do
echo  ${DIR}
done

现在我需要帮助将它们组合在一起,以便脚本可以将与​​模式匹配的所有目录(包括子内容)复制到另一个位置。

提前致谢。

我不确定你的环境,但我猜你尝试这样做:

cp -r src_dir/??_?? dest_dir

请检查这是否是您想要的。它搜索格式为 xx_yy/ab_cd/&&_$$ (2char_2char) 的目录并将内容复制到新目录 .

usage : ./script.sh

cat script.sh

#!/bin/bash

MYDIR="/media/test/"
NEWDIRPATH="/media/test_new"
DIRS=`ls -l $MYDIR | grep "^d" | awk '{print }'`
for DIR in $DIRS
do
        total_characters=`echo $DIR | wc -m`
        if [ $total_characters -eq 6 ]; then
                has_underscore=`echo "$DIR" | grep "_"`
                if [ "$has_underscore" != "" ]; then
                        echo "${DIR}"
                        start_string_count=`echo $DIR | awk -F '_' '{print }' | wc -m`
                        end_string_count=`echo $DIR | awk -F '_' '{print }' | wc -m`
                        echo "start_string_count => $start_string_count ; end_string_count => $end_string_count"
                        if [ $start_string_count -eq 3 ] && [ $end_string_count -eq 3 ]; then
                                mkdir -p $NEWDIRPATH/"$DIR"_new
                                cp -r $DIR $NEWDIRPATH/"$DIR"_new
                        fi
                fi
        fi
done

要有选择地将整个目录结构复制到相似的目录结构,同时过滤内容,通常最好的办法是归档原始目录并取消归档。例如,使用 GNU Tar:

$ mkdir destdir
$ tar -c /media/test/{en_US,de_DE} | tar -C destdir -x --strip-components=1

在此示例中,/media/test 目录结构在 destdir 下部分重新创建,不包括 /media 前缀(感谢 --strip-components=1)。

左侧tar 仅归档与我们指定的模式匹配的directories/paths。存档是在该命令的标准输出上生成的,它通过管道传输到右侧的解码 tar-C 告诉它切换到目标目录。它在那里提取文件,删除前导路径组件。

$ ls destdir
test
$ ls destdir/test
en_US de_DE

当然,您的特定示例测试用例很容易用 cp -a:

处理
$ mkdir destdir
$ cp -a /media/test/{en_US,de_DE} destdir

如果模式很复杂,涉及在源目录层次结构的更深 and/or 不同级别的子树 material 的多个选择,那么您需要更通用的方法,如果您希望执行在仅指定源模式的单个批处理命令中复制。

这是 10 人份的开胃菜:
您将不得不添加所需的额外检查和平衡,但这应该会给您一个良好的开端。

#!/bin/bash
# assumes  is source to search and  to destination to copy to
subdirs=`find  -name ??_?? -print`
echo $subdirs
for x in $subdirs
do
        echo $x
        cp -a $x 
done