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

标签 regex linux bash grep sh

有什么方法可以使用 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 $10}'`
for DIR in $DIRS
do
echo  ${DIR}
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 仅归档与我们指定的模式匹配的目录/路径。存档是在该命令的标准输出上生成的,它通过管道传输到右侧的解码 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

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

关于regex - Bash 复制所有内容与模式匹配的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32438653/

相关文章:

c# - 正则表达式查找特殊模式

python - 在Linux上使用python接收多播UDP数据报

c - Linux写整数

python - 拆分命令 - 选择输出名称

linux - 这个shell脚本有什么作用?什么是标题复制和行复制?变量?

java - 正则表达式混淆

regex - 如何使用 Vim 或 Perl 在文件中的特定行上方插入一行?

regex - 如何在正则表达式中匹配不同的组

linux - Raspberry Pi 在 Airport Extreme 上自动挂载 NAS

linux - Vmrun超时命令