Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use xargs as part of a directory path?

Tags:

bash

unix

cp

xargs

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?

like image 243
kslnet Avatar asked Sep 05 '25 03:09

kslnet


2 Answers

This xargs should work:

cd /tmp/dest_dir

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

Explanation:

  • Glob pattern ??-?? matches any 2 characters then - followed by any 2 characters
  • \ls -d: Directories are listed as plain files
  • xargs -I{} cp .. command runs for each entry found by ls -d command and copies goodfile from source to destination. {} is placeholder for each entry from ls -d
like image 157
anubhava Avatar answered Sep 08 '25 07:09

anubhava


Another solution but without xargs

find . -iname "??-??" -exec cp goodfile "{}"  \;
like image 31
Joao Vitorino Avatar answered Sep 08 '25 07:09

Joao Vitorino