eddie kuo
eddie kuo

Reputation: 728

How to concatenate a file to multiple files?

I want concatenate text to all the files in dir. I use for to complete this job like the following code. I want to know is there has a more concise code to do the same thing?

for fn in dir/*; do
  cat text >> $fn
done

Upvotes: 6

Views: 230

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 208107

You can do them all concisely and in parallel with GNU Parallel:

parallel 'cat text >>' ::: dir/*

Upvotes: 3

John1024
John1024

Reputation: 113994

If text is a file name, try:

tee -a dir/* <text >/dev/null

If text is actually some text that you want to append, then in bash:

tee -a dir/* <<<"text" >/dev/null

tee is a utility that reads from standard input and writes it to any number of files on its command line. It also copies the standard input to standard out which is why >/dev/null is used above. The -a option tells tee to append rather than overwrite.

Variation

As suggested by kvantour, it may be more clear to put the redirection for input at the beginning of the line:

<text tee -a dir/* >/dev/null

(In the above, text is assumed to be a filename)

Upvotes: 7

KamilCuk
KamilCuk

Reputation: 142080

There are problems with your code:

  • If no files in dir exists, you will write text to a file named * literally.
  • $fn expansion is unquoted!

I would:

find dir -maxdepth 1 -type f -exec sh -c 'cat text >> "$1"' _ {} \;

which I do not think is more concise.

Upvotes: 4

Related Questions