Linux Using xargs to Copy All Files in Directory or Subdirectory

To copy all the files, for example, mp3 files in a directory/subdirectory to another directory in Linux, you can use the xargs command and the find but by using "sed" tool to also filter the quotes of file names.

The command is pretty simple which is write down below.

$> find . -name "*.mp3" | sed -r "s/'/\\\\\'/g" | xargs -t -I '{}' cp '{}' /media/disk/Music/


What it does, is that, it will find any files that ends with *.mp3 file extension from the current directory the command is being executed, and sed will will apply a regular expression to filter the quotes and replace it with "\'" (a slash and a single quote). After this, xargs command will catch the lines outputed by the find command but filtered with sed and executes a cp command and directs it to /media directory.

find options:
-name = specifies the name to find

sed options:
-r = will do an extended regular expression

xargs options:
-t = print the command line (which is the cp) in the standard error output before executing the command
-I = replaces the brackets '{}' with the input from find and sed (or the initial-arguments with names read from standard input) and it's separator is the new line

Comments

Nehemiah said…
Thanks man !!! That worked well !!!

Popular posts from this blog

LVM: How to remove a volume using pvremove

Using Oracle 11g thru VirtualBox appliance in Mac OS X Lion

Use Shell Editor for Eclipse for editing bash, ksh, csh in Unix/Linux system