Monday, 26 November 2012

Find all files and move to a target directory from the Linux command line

For this example, we're going to be moving all .mp3 files from the subdirectories of the current directory into current directory.

To do this, we need to combine two different commands. To find all the files in the current directory and its subdirectories, we use the find command:
 find -name \*.mp3  

The \ escapes the *, so it's interpreted as a wild card on the command line. The -name argument allows us to check only the file names.

To move files around on the command line, we use the mv command, and for our example, we add the -t argument, which lets us define the target directory:
 mv -t <target-directory> <file-to-move>
where target-directory is where we want to move the file to, and file-to-move is the file we want to move.

With a bit of command-line magic, we can combine these commands using the -exec switch on find, to give us our final command:
 find -name \*.mp3 -exec mv -t . {} \+  
-exec takes the command we want to execute, and {} \+ appends each find result to the command, which in our case is mv. So the above line will find all files end in .mp3 and move them to the current directory.

No comments:

Post a Comment

Please leave a comment if you find this blog helpful or interesting! I'd love to hear from you!