Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append file to file in bash without cat

Tags:

file

bash

append

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?

like image 958
nebuch Avatar asked Sep 04 '15 18:09

nebuch


People also ask

How do I append a file in Bash?

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.

How do I add data to an existing file in Linux?

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.


2 Answers

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.

like image 62
chepner Avatar answered Oct 20 '22 12:10

chepner


# 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 
like image 42
mon Avatar answered Oct 20 '22 13:10

mon