Skip navigation

This one was eluding me for a while, what I simple wanted is to use cp (copy) with xargs to duplicate files in a different destination. What I had used before is the command copy in combination with find, via the exec argument like this:

find . -maxdepth 1 -name 'in*.css' -exec cp '{}' ~/src/Report/geo_portal/t/tmpl/src/css/ \;

But I wanted to use xargs, since I pretty much like its elegance and possibilites. The example below is a real one I used in BSD 7:

find . -name '*.html' | xargs grep -l 'Datasets' | xargs -J % cp -rp % ~/src/Report/playground/t/tmpl/src/css/

The explanation lies in the xargs manual, albeit a bit obscure:

-J replstr
If this option is specified, xargs will use the data read from standard input to replace the first occurrence of replstr instead of appending that data after all other arguments. This option will not affect how many arguments will be read from input (-n), or the size of the command(s) xargs will generate (-s). The option just moves where those arguments will be placed in the command(s) that are executed. The replstr must show up as a distinct argument to xargs. It will not be recognized if, for instance, it is in the middle of a quoted string. Furthermore, only the first occurrence of the replstr will be replaced. For example, the following command will copy the list of files and directories which start with an uppercase letter in the current directory to destdir:

/bin/ls -1d [A-Z]* | xargs -J % cp -rp % destdir

Note: When I wanted to use it in my Cygwin shell I had to replace the option “-J” with “-I”. In this example I copied every image lighter that 3000k into other folder.

ls -ltra | awk '{print $5," ",$9}' | awk '$1 < 3000' | awk '/gif|png|jpg/ {print $2}' | xargs -I % cp -rp % /web/R/images/

Advertisements

2 Comments

  1. Use a subshell and tar

    tar cf – . | ( cd new ; tar cf – )

    Lots of cpio variants to do this too, not tested this example but it looks right. Will also copy permissions and ownerships, as will cpio.

    • Sweet!. I’ll try it as well of the cpio variants you mention, which didn’t know about yet. Thanks Francis!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: