I can create a range of files, say for example:
touch file{A..Z}.txt
What then would be the simplest solution for directing output to this range?
For example: echo 'hello, world' to all files in range of {A..Z}.
I can create a range of files, say for example:
touch file{A..Z}.txt
What then would be the simplest solution for directing output to this range?
For example: echo 'hello, world' to all files in range of {A..Z}.
If you're using this command to create files:
touch file{A..Z}.txt
You can equally write the same text to them (and create them) using the same expansion:
echo hello, world | tee file{A..Z}.txt
The tee command will also write to stdout, so you'll get a copy written to your terminal too. Redirect that to /dev/null if you don't want it:
echo hello, world | tee file{A..Z}.txt >/dev/null
Run man tee on your local system for information about the command. For example the -a flag will append the text to the set of files.
The expansion itself is performed by the shell, which is bash in many cases. See man bash for details.
In zsh:
echo new test > file{A..Z}.txt
That's assuming the multios option has not been disabled.
Effectively, when a fd is redirected several times for writing (with >, >>, 1<>, >!, >| redirection operators but that also applies with |...) in zsh, zsh redirects it instead to a pipe, and at the other end of the pipe, there's a background zsh process that despatches the data to all the targets in a tee-like fashion.
If the noclobber option is on, and fileK.txt for instance already existed, the redirection is aborted and the command not run at the point of opening it, so fileK.txt will not be clobber, but fileA.txt to fileJ.txt will have be opened (and created with 0 size).
Note that all those files are opened concurrently, so, like with tee, you'll run into the limit on the number of open file descriptors if redirecting to too many files:
$ echo test > file{A..Z}{A..Z}{A..Z}.txt
zsh: multio failed for fd 3: too many open files
$ echo test | tee file{A..Z}{A..Z}{A..Z}.txt
tee: fileBNH.txt: Too many open files
tee: fileBNI.txt: Too many open files
tee: fileBNJ.txt: Too many open files
[...]
tee: fileZZZ.txt: Too many open files
test
Here, with a command like echo which hardly costs anything do run (less anyway than the overhead of creating pipes and shoving data through them that the tee-like behaviour entails), you could open, populate and close the files in series instead of in parallel and have echo write directly to the files:
for f (file{A..Z}.txt) echo new test > $f
If you have already created your files and only want to append new text, you can use tee command with -a option:
echo "new text" | tee -a file{A..Z}.txt
To add contents of a file (e.g. file0) to your files:
<file0 tee -a file{A..Z}.txt