Jonathan Sternberg
Jonathan Sternberg

Reputation: 6647

Regex find and copy in bash (preserving folder structure)?

I have a folder with a bunch of log files. Each set of log files is in a folder detailing the time and date that the program was run. Inside these log folders, I've got some video files that I want to extract. All I want is the video files, nothing else. I tried using this command to only copy the video files, but it didn't work because a directory didn't exist.

.rmv is the file extension of the files I want.

$ find . -regex ".*\.rmv" -type f -exec cp '{}' /copy/to/here/'{}'

If I have a folder structure such as:

|--root  
   |  
   |--folder1  
   |  |  
   |  |--file.rmv  
   |  
   |--folder2  
      |  
      |--file2.rmv  

How can I get it to copy to copy/to/here with it copying the structure of folder1 and folder2 in the destination directory?

Upvotes: 3

Views: 5958

Answers (4)

K7g
K7g

Reputation: 111

cp has argument --parents so the shortest way to do what you want is:

find root -name '*.rmv' -type f -exec cp --parents "{}" /copy/to/here \;

Upvotes: 11

user180100
user180100

Reputation:

Assuming src is your root and dst is your /copy/to/here

#!/bin/sh

find . -name *.rmv | while read f
do
       path=$(dirname "$f" | sed -re 's/src(\/)?/dst\1/')
       echo "$f -> $path"
       mkdir -p "$path"
       cp "$f" "$path"
done

putting this in cp.sh and running ./cp.sh from the directory over root

Output:

./src/folder1/file.rmv -> ./dst/folder1
./src/My File.rmv -> ./dst
./src/folder2/file2.rmv -> ./dst/folder2

EDIT: improved script version (thanks for the comment)

Upvotes: -1

Dennis Williamson
Dennis Williamson

Reputation: 360015

I would just use rsync.

Upvotes: 2

martin clayton
martin clayton

Reputation: 78105

The {} represents the full path of the found file, so your cp command evaluate to this sort of thing:

cp /root/folder1/file.rmv /copy/to/here/root/folder1/file.rmv

If you just drop the second {} it will instead be

cp /root/folder1/file.rmv /copy/to/here

the copy-file-to-directory form of cp, which should do the trick.

Also, instead of -regex, yor could just use the -name operand:

find root -name '*.rmv' -type f -exec cp {} /copy/to/here \;

Upvotes: 0

Related Questions