Search code examples
bashunixxargscp

Can I use xargs as part of a directory path?


I have this directory structure:

% ls /tmp/source_dir/
aa-aa/  bb-bb/  cc-cc/  morejunk/  somejunk/

% ls /tmp/dest_dir
aa-aa/  bb-bb/  blah/  blahblah/

For every directory in dest_dir matching ??-??, I want to copy a corresponding file "goodfile" from the source_dir. I have tried the following to no avail:

% cd /tmp/dest_dir

/tmp/dest_dir% \ls -d ??-?? | xargs cp /tmp/source_dir/{}/goodfile {}
cp: cannot stat `/tmp/source_dir/{}/goodfile': No such file or directory
cp: cannot stat `{}': No such file or directory
cp: omitting directory `aa-aa'

/tmp/dest_dir% \ls -d ??-?? | xargs bash -c "cp /tmp/source_dir/{$0}/goodfile {$0}"
cp: cannot stat `/tmp/source_dir/{/bin/bash}/goodfile': No such file or directory

Surely there's a way to do this without writing a separate script?


Solution

  • This xargs should work:

    cd /tmp/dest_dir
    
    \ls -d ??-?? | xargs -I{} cp /tmp/source_dir/{}/goodfile {}