domi771
domi771

Reputation: 450

Linux - How to copy recursive from each folder N files and keep same folder structure

I need to copy from each sub folder 10 files/images recursively.

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

result should be:

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

Directory structure should be the same but each folder should have max. 10 random files from each original folder in it.

How can I do this with a shell script?

Upvotes: 0

Views: 664

Answers (1)

cazorla19
cazorla19

Reputation: 284

I guess you don't want to copy all files (which suggested by cp -r command), but only n files.

Let's say we have a directory called foo and need to move n=10 files from each subdirectory to the specific location called bar. So, shell script loop will look like this.

#!/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

Upvotes: 3

Related Questions