0

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)?

learner
  • 3
  • 2
  • This sounds a bit homeworky, so as a rough pointer, you can use `find ... -exec` to execute commands on all files in a directory. – Ulrich Schwarz Jul 21 '18 at 09:03
  • Generally you wouldn't use `cat` to do that. You'd use something like `find` and `cp`. – roaima Jul 21 '18 at 11:03

1 Answers1

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
  • 320,670
  • 36
  • 633
  • 936