【问题标题】:Linux - How to copy recursive from each folder N files and keep same folder structureLinux - 如何从每个文件夹 N 个文件中复制递归并保持相同的文件夹结构
【发布时间】:2016-10-17 11:33:17
【问题描述】:

我需要从每个子文件夹中递归地复制 10 个文件/图像。

/dir1 
├── subdir1 
│   ├── file1 
│   └── fileN
│
├── subdir2 
│   ├── file1 
│   └── fileN 
│
├── subdir3 
│   ├── file1 
│   └── fileN 
│
└── subdirN 
    ├── file1 
    └── fileN 
... 

结果应该是:

/newdir1 
├── subdir1 
│   ├── file1 
│   └── file10 
│
├── subdir2 
│   ├── file1 
│   └── file10 
│
├── subdir3 
│   ├── file1 
│   └── file10 
│
└── subdirN 
    ├── file1 
    └── file10 
... 

目录结构应该相同,但每个文件夹应该有最大值。每个原始文件夹中的 10 个随机文件。

如何使用 shell 脚本做到这一点?

【问题讨论】:

  • 使用cp 命令和-r 选项。
  • 我想从每个文件夹复制,例如。 10 个文件。每个文件夹中有不同数量的文件。
  • 前 10 个,后 10 个,或者随机 10 个?
  • 随机 :) 但任何作品
  • 好的,你想把它们复制到哪里,到一个目录中?

标签: linux shell command


【解决方案1】:

我猜你不想复制所有文件(由cp -r 命令建议),但只复制 n 个文件。

假设我们有一个名为foo 的目录,需要将n=10 文件从每个子目录移动到名为bar 的特定位置。因此,shell 脚本循环将如下所示。

#!/bin/bash

for subdir in $(find ~/foo -type d); do
  subdir_relative=$(echo $subdir | sed 's:.*foo/::g')
  mkdir "$subdir_relative"
  for file in $(find "$subdir" -type f | head -n 10); do
    cp "$file" "~/bar/$subdir_relative/"
  done
done

【讨论】:

  • 谢谢!我的描述并不完美。我想保留当前的文件夹结构。
  • 你会的,别担心。它只是复制文件,而不是移动
  • 您的代码失败,目录名称包含空格,例如a b c
  • 当然,我修复了这个将目录名称包装成双引号的错误;感谢关注
  • 我的意思是,在 bar 文件夹中,foo 文件夹中的所有子文件夹都应该仍然存在,并且每个子文件夹中都应该有 N 个(例如 10 个)文件。并非所有文件都应该在 bar 文件夹中。希望它可以理解
猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 2018-12-11
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 2021-02-22
相关资源
最近更新 更多