- How to append multiple lines to a file
- 10 Answers 10
- Adding a line of text to multiple files
- 4 Answers 4
- A shell script like this can work:
- You must log in to answer this question.
- Related
- Hot Network Questions
- Subscribe to RSS
- How can I append and prepend some text to all files in a folder in Linux
- 4 Answers 4
- File: BEGIN
- File: END
- Run commands:
- How to prepend a line to all files in a directory?
- 3 Answers 3
- Solution
- Explanation
How to append multiple lines to a file
I am writing a bash script to look for a file if it doesn’t exist then create it and append this to it:
Host localhost ForwardAgent yes
10 Answers 10
# possibility 1: echo "line 1" >> greetings.txt echo "line 2" >> greetings.txt # possibility 2: echo "line 1 line 2" >> greetings.txt # possibility 3: cat > greetings.txt line 1 line 2 EOT # possibility 4 (more about input than output): arr=( 'line 1' 'line 2' ); printf '%s\n' "$" >> greetings.txt
If sudo (other user privileges) is needed to write to the file, use this:
# possibility 1: echo "line 1" | sudo tee -a greetings.txt > /dev/null # possibility 3: sudo tee -a greetings.txt > /dev/null
@ott-- You don't need a real subshell (i.e. can save one new process), this is enough: < echo "line 1" ; echo "line 2"; >>>greetings.txt
echo -e "Hello \nWorld \n" >> greetings.txt
printf '%s\n %s\n' 'Host localhost' 'ForwardAgent yes' >> file.txt
Or, if it's a literal tab that you want (rather than the four spaces in your question):
printf '%s\n\t%s\n' 'Host localhost' 'ForwardAgent yes' >> file.txt
You can achieve the same effect with echo , but exactly how varies from implementation to implementation, whereas printf is consistent.
Another approach is to use tee
A few choice lines from tee 's man page:
The tee utility copies standard input to standard output, making a copy in zero or more files.
-a - Append the output to the files rather than overwriting them.
+1 tee tends to work with paths that require sudo (solutions that use > >> <
Here is an example to append multiple lines in a file:
< echo ' directory "/var/cache/bind";' echo ' listen-on < 127.0.0.1; >;' echo ' listen-on-v6 < none; >;' echo ' version "";' echo ' auth-nxdomain no;' echo ' forward only;' echo ' forwarders < 8.8.8.8; 8.8.4.4; >;' echo ' dnssec-enable no;' echo ' dnssec-validation no;' > >> your_file.txt
It is worth to note that this variant is part of the ShellCheck recommendation github.com/koalaman/shellcheck/wiki/SC2129
SED can append a line to the end of a file like so:
sed -i '$ a text to be inserted' fileName.file
$ selects end of file, the a tells it to append, and after this comes the text that is to be inserted. Then of course the file name.
Does this approach have any added benefit than other solutions?
Yes, this approach has the added benefit of appending to any files return in a search, such as this: find . -name "*.html" -exec sed -i '$ a