How could we use cat command to copy a file's contents to all the files under a directory (recursively -I mean each and every file)?
Asked
Active
Viewed 1,431 times
1 Answers
0
To overwrite each file in an entire directory hierarchy with the contents of the file data
:
find . -type f ! -path './data' -exec sh -c 'tee "$@" <data >/dev/null' sh {} +
If you want to append the contents of data
, then use tee -a
in the above.
The ! -path ./data
is to avoid modifying the file that we are reading from.
The child shell will get a bunch of pathnames from find
and will use tee
to distribute the contents of data
to these files.
To use cat
instead of tee
:
find . -type f ! -path './data' -exec sh -c '
for pathname do
cat data >"$pathname"
done' sh {} +
Here, to append the data, use >>
in place of >
.
Run this in a directory where it's safe to do so. Running it in your home directory will destroy all your files. To recover from that, you will need to restore from a recent backup. Never run commands that you've copied and pasted from the internet, without knowing what they do or may do.
Related:

Kusalananda
- 333,661
find ... -exec
to execute commands on all files in a directory. – Ulrich Schwarz Jul 21 '18 at 09:03cat
to do that. You'd use something likefind
andcp
. – Chris Davies Jul 21 '18 at 11:03