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

closed as unclear what you're asking by roaima, Jeff Schaller, Romeo Ninov, Jesse_b, slm Jul 21 '18 at 15:33

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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 9: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

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.


Not the answer you're looking for? Browse other questions tagged or ask your own question.