Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a file to multiple files?

Tags:

file

bash

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
like image 761
eddie kuo Avatar asked Aug 07 '20 06:08

eddie kuo


People also ask

How do you concatenate files?

To choose the merge option, click the arrow next to the Merge button and select the desired merge option. Once complete, the files are merged. If there are multiple files you want to merge at once, you can select multiple files by holding down the Ctrl and selecting each file you want to merge.

How can we concatenate two files and save the output in another file?

Type the cat command followed by the file or files you want to add to the end of an existing file. Then, type two output redirection symbols ( >> ) followed by the name of the existing file you want to add to.

Which command is used to concatenate files?

Introducing cat Command To concatenate files, we'll use the cat (short for concatenate) command.

What command is best for concatenating two files together?

The cat (short for “concatenate”) command is one of the most commonly used commands in Linux as well as other UNIX-like operating systems, used to concatenate files and print on the standard output.


3 Answers

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)

like image 65
John1024 Avatar answered Oct 26 '22 23:10

John1024


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.

like image 26
KamilCuk Avatar answered Oct 27 '22 00:10

KamilCuk


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

parallel 'cat text >>' ::: dir/*
like image 33
Mark Setchell Avatar answered Oct 26 '22 22:10

Mark Setchell