It's easy to append an existing file to another file with cat
: cat file1 >> file2
Sometimes I have read what people wrote, "do not use cat
unless you are concatenating two files." This is sensible. One does not really need cat if it is taking only one argument: cat file | xargs program
is worse than xargs program < file
.
So how do I append a file to another file without cat? Neither < file1 >> file2
nor >> file2 < file1
work. If I must call a program to do this, what is the orthodox way?
To make a new file in Bash, you normally use > for redirection, but to append to an existing file, you would use >> . Take a look at the examples below to see how it works. To append some text to the end of a file, you can use echo and redirect the output to be appended to a file.
The tee command copies the text from standard input and writes it to the standard output file. The tee provides -a option to append the text to the file. This is how we append the text into a file in Linux.
This is an orthodox use of cat
. The "useless use of cat
" involves using cat
to read the contents of a single file and pipe them to another program which could just as easily read directly from the file using input redirection. Here, cat
is doing all the reading and writing; there isn't anything simpler you could replace it with, since bash
does not provide a built-in that reads from standard input and writes to standard output.
# Redirecting Input 'from' file to Command Substitution as "echo" argument
# "echo" stdout write 'to' file
echo "$(<from)" > to
# Redirecting Input 'from' file to Command Substitution as "printf" argument
# "printf" stdout write 'to' file
printf "%s" "$(<from)" > to
# Redirecting Input 'from' file to "sed" and stdout write 'to' file
sed -n '/.*/p' <from > to
envsubst
In normal operation mode, standard input is copied to standard
output, with references to environment variables of the form ‘$VARIABLE’`
or ‘${VARIABLE}’ being replaced with the corresponding values.
# create file with name 'template'
echo '$buf' > template
# Redirecting Input 'from' file to Command Substitution
# Assign to 'buf' variable and export
# envsubst standard input from 'template' file copied 'to' file
export buf="$(<from)" && envsubst < template > to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With