Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix shell file copy flattening folder structure

Tags:

shell

unix

On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?

Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.

Example: I need to copy every .txt file in the following hierarchy

/foo/a.txt /foo/x.jpg /foo/bar/a.txt /foo/bar/c.jpg /foo/bar/b.txt 

To a folder named 'dest' and get:

/dest/a.txt /dest/b.txt 
like image 681
Sergio Acosta Avatar asked Aug 26 '08 09:08

Sergio Acosta


People also ask

How do I flatten a folder structure?

There's no reason to use special tools or even scripting. Just use the search function in Explorer. Open the folder you wish to flatten in Explorer. Create a new folder, select all files (but not folders), and drag them to that folder (This will avoid getting two copies of those files.)

How do I copy a directory structure in Unix?

In order to copy a directory on Linux, you have to execute the “cp” command with the “-R” option for recursive and specify the source and destination directories to be copied.

What is flatten folder hierarchy?

Flattening a folder means moving all the files from their various subfolders into one parent folder. You may want to do this to ease archiving, or to rearrange files that are stored in subfolders on a daily basis into a monthly wrap-up folder, for instance.


1 Answers

In bash:

find /foo -iname '*.txt' -exec cp \{\} /dest/ \; 

find will find all the files under the path /foo matching the wildcard *.txt, case insensitively (That's what -iname means). For each file, find will execute cp {} /dest/, with the found file in place of {}.

like image 113
Magnus Hoff Avatar answered Sep 24 '22 01:09

Magnus Hoff