Sadam
Sadam

Reputation: 117

How to copy a file to all subdirectories?

How can I paste read-me.jpg file into all sub-directories? Here is a command to create a new file in all subdirectories.

for dir in `find . -type d` ; do echo "mywebsite.com" > $dir/downloadedfrom.txt ; done

But I want to copy jpg file into all subdirectories instead.

Directory List:

2011
2012
2009
2019
2021
2000/2001/..../2010
...
...

already tried with this command but no output

for dir in `find . -type d` ; cp read-me.jpg > $dir ; done

Upvotes: 2

Views: 4710

Answers (2)

sourcloud
sourcloud

Reputation: 124

You tried to redirect cp's output into $dir but instead we should specify the destination $dir/read-me.jpg as the second argument of cp

for dir in `find . -type d` ; do cp read-me.jpg $dir/read-me.jpg ; done

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 362187

cp and > don't mix. cp's syntax is cp source destination with no redirections.

When possible use find -exec to execute a command on each result. It's simpler and less error prone than looping over its output.

find . -type d -exec cp read-me.jpg {} ';'

When using -exec, {} is a placeholder for the paths that are found, and ';' is a required piece of syntax to signal the end of the -exec action (in case there are additional find options following the -exec).

Upvotes: 5

Related Questions