Link to home
Start Free TrialLog in
Avatar of Randy Johnson
Randy JohnsonFlag for United States of America

asked on

Doing a copy of a file to sub-dirs

Here is a directory structure

a
b
c
d
e
f
g


all of the above are directorties

I want to copy file file.txt to each of those directories

i thought cp file.txt */  would do it but that did not work.


any ideas?

Thanks!

Randy
Avatar of owensleftfoot
owensleftfoot

#!/bin/bash

for directory in a b c d e f g
 do
cp file.txt $directory/
 done
ls -d a b c d e f g|xargs -n1 cp file.txt
Hi,

  For rugdog's script/comand, I did some modification:
----
ls -d * |xargs -n1 cp file.txt
----
Wesly
Wesly,
   that's dangerous assuming file.txt, a, b, c, d, e, f and g are not the only files in the current directory. if you have more files all will end being like file.txt.
Avatar of Tintin
If you don't want to type in the directories and/or they will vary in name and quantity, do:

find /path/to/dirs -type d -maxdepth 1 -exec cp /path/to/file.txt {} \;
Avatar of Randy Johnson

ASKER

TinTin,

Please describe your command so I can understand what each part does.

Thanks!

Randy
based on rugdog command, if you want to copy the file to all subdirectories:

# ls -F |grep "/" |xargs -n1 cp file.txt
ASKER CERTIFIED SOLUTION
Avatar of rugdog
rugdog
Flag of Mexico image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have learned to use perl from command line for times like this. I liken it to "Using the force"

Assuming you are in the parent directory of a->g:

perl -e 'my @arry=(a..g); for (@arry) {system("cp file.txt ./$_");}'

Highest regards,

~K Black
Irvine, Ca.
rugdog's version is certainly the shortest and simpliest.

To expand of the find command:

find /path/to/dirs -type d -maxdepth 1 -exec cp /path/to/file.txt {} \;

/path/to/dirs - Path to the directory to start searching from
-type d  - Only match directories
-maxdepth 1 - Don't descend to subdirectories
-exec  fork a command
cp /path/to/file.txt {} \;   - Copy file.txt to the matched directory, which is specified with {}
tintin, i found that your find command statement will also copy file.txt to the directory i start searching from.
I can't possibly see how you would get two different versions of file.txt being copied.  Are you using correct paths?