Append Lines to a File in Linux
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
1. Introduction
In this tutorial, we’re going to explore several ways to append one or more lines to a file in Linux using Bash commands.
First, we’ll examine the most common commands like echo, printf, and cat. Second, we’ll take a look at the tee command, a lesser-known but useful Bash utility.
2. The echo Command
The echo command is one of the most commonly and widely used built-in commands for Linux Bash. Usually, we can use it to display a string to standard output, which is the terminal by default:
echo "This line will be displayed to the terminal"
Now, we’re going to change the default standard output and divert the input string to a file. This capability is provided by the redirection operator (>). If the file specified below already contains some data, the data will be lost:
echo "This line will be written into the file" > file.txt
In order to append a line to our file.txt and not overwrite its contents, we need to use another redirection operator (>>):
echo "This line will be appended to the file" >> file.txt
Note that the ‘>’ and ‘>>’ operators are not dependent on the echo command and they can redirect the output of any command:
ls -al >> result.txt find . -type f >> result.txt
Moreover, we can enable the interpretation of backslash escapes using the -e option. So, some special characters like the new line character ‘\n’ will be recognized and we can append multiple lines to a file:
echo -e "line3\n line4\n line5\n" >> file.txt
3. The printf Command
The printf command is similar to the C function with the same name. It prints any arguments to standard output in the format:
Let’s build an example and append a new line to our file using the redirection operator:
Unlike the echo command, we can see that the printf‘s syntax is simpler when we need to append multiple lines. Here, we don’t have to specify special options in order to use the newline character:
printf "line7\nline8!" >> file.txt
4. The cat Command
The cat command concatenates files or standard input to standard output.
It uses a syntax similar to the echo command:
The difference is that, instead of a string as a parameter, cat accepts one or more files and copies its contents to the standard output, in the specified order.
Let’s suppose we already have some lines in file1.txt and we want to append them to result.txt
cat file1.txt >> result.txt cat file1.txt file2.txt file3.txt >> result.txt
Next, we’re going to remove the input file from the command:
In this case, the cat command will read from the terminal and appends the data to the file.txt.
So, let’s then type something into the terminal including new lines and then press CTRL + D to exit:
[email protected]:~/Desktop/baeldung/append-lines-to-a-file$ cat >> file.txt line1 using cat command line2 using cat command
This will add two lines to the end of file.txt.
5. The tee Command
Another interesting and useful Bash command is the tee command. It reads data from standard input and writes it to the standard output and to files:
tee [OPTION] [FILE(s)] tee file1.txt tee file1.txt file2.txt
In order to append the input to the file and not overwrite its contents, we need to apply the -a option:
[email protected]:~/Desktop/baeldung/append-lines-to-a-file$ tee -a file.txt line1 using tee command
Once we hit Enter, we’ll actually see our same line repeated back to us:
[email protected]:~/Desktop/baeldung/append-lines-to-a-file$ tee -a file.txt line1 using tee command line1 using tee command
This is because, by default, the terminal acts as both standard input and standard output.
We can continue to input how many lines we want and hit the Enter key after each line. We’ll notice that each line will be duplicated in the terminal and also appended to our file.txt:
[email protected]:~/Desktop/baeldung/append-lines-to-a-file$ tee -a file.txt line1 using tee command line1 using tee command line2 using tee command line2 using tee command
Now, let’s suppose we don’t want to append the input to the terminal, but only to a file. This is also possible with the tee command. Thus, we can remove the file parameter and redirect the standard input to our file.txt by using the redirection operator:
[email protected]:~/Desktop/baeldung/append-lines-to-a-file$ tee >> file.txt line3 using tee command
Finally, let’s take a look at the file.txt‘s contents:
This line will be written into the file This line will be appended to the file line3 line4 line5 line6 line7 line8 line1 using cat command line2 using cat command line1 using tee command line2 using tee command line3 using tee command
6. Conclusion
In this tutorial, we’ve described a few ways that help us append one or more lines to a file in Linux.
First, we’ve studied the echo, printf and cat Bash commands and learned how we can combine them with the redirection operator in order to append some text to a file. We’ve also learned how to append the content of one or more files to another file.
Second, we’ve examined the lesser-known tee command that already has a built-in mechanism of appending some text to a file and doesn’t necessarily need the redirection operator.
Command to append line to a text file without opening an editor
You can append a line of text to a file by using the >> operator:
echo "hello world" >> my_file.txt
echo "alias list='ls -cl --group-directories-first'" >> config.fish
I use echo myself, but be careful, if you only specify one > then the file will truncate, not append. for a safer command you can use sed: sed -i ‘$a hello world’ filename
explanation: -i will update the file (otherwise it will just print the result to stdout), $ is regex that will match the end of the file, and a appends the following text to filename.
echo «hello world» >> my_file.txt does not create a new last line with HW , but add it to the string of the last line.
Maybe «Hello World» @7wp 🙂 It’s echo that adds the line break (making it a line as opposed to just a bunch of characters). You can switch off the line break at the end with -n .
Adding to Stefano’s answer, you can also use cat :
$ cat >> config.fish alias list='ls -cl --group-directories-first' > EOF
I often use this method but recently got caught when I pasted in a text that included some (escape) codes. It didn’t complain but when I checked the file there were chunks of pasted text missing. So use it with care!
@elmclose Sorry, which method? They work differently with respect to metacharacters. I think the second one doesn’t do anything with them, though there might be a few exceptions.
I meant EOF method. Very convenient and useful when you type or paste in readable text. But codes in my text confused the process. The file was a bash script that kept failing. Took me a while before I discovered what had happened.
There’s plenty of methods of appending to file without opening text editors, particularly via multiple available text processing utilities in Ubuntu. In general, anything that allows us to perform open() syscall with O_APPEND flag added, can be used to append to a file.
- GNU version of dd utility can append data to file with conv=notrunc oflag=append
printf "\nalias list='ls -cl --group-directories-first'\n" | dd conv=notrunc oflag=append bs=1 of=config.fish
sed -i '$a alias list='"'"'ls -cl --group-directories-first'"'" config.fish
#!/usr/bin/env python3 # read bytes from stdin, append to specified file import sys with open(sys.argv[1],'ab') as f: f.write(sys.stdin.buffer.read())
See also:
How to append output to the end of a text file
If file_to_append_to does not exist, it will be created.
$ echo "hello" > file $ echo "world" >> file $ cat file hello world
The problem is that echo removes the newlines from the string. How do you append to a file a string which contains newlines?
echo does not remove newlines from the string. If you fail to properly quote the argument, then the shell will split the string and pass arguments to echo and echo never even sees the newlines.
@Pmpr note that echo is not part of the solution, it is only part of the example I typed, and there are no escape sequences in the example.
echo "hello world" >> read.txt cat read.txt echo "hello siva" >> read.txt cat read.txt
then the output should be
hello world # from 1st echo command hello world # from 2nd echo command hello siva
echo "hello tom" > read.txt cat read.txt
You can use the >> operator. This will append data from a command to the end of a text file.
echo "Hi this is a test" >> textfile.txt
Do this a couple of times and then run:
You’ll see your text has been appended several times to the textfile.txt file.
Use command >> file_to_append_to to append to a file.
For example echo «Hello» >> testFile.txt
CAUTION: if you only use a single > you will overwrite the contents of the file. To ensure that doesn’t ever happen, you can add set -o noclobber to your .bashrc .
This ensures that if you accidentally type command > file_to_append_to to an existing file, it will alert you that the file exists already. Sample error message: file exists: testFile.txt
Thus, when you use > it will only allow you to create a new file, not overwrite an existing file.
Using tee with option -a (—append) allows you to append to multiple files at once and also to use sudo (very useful when appending to protected files). Besides that, it is interesting if you need to use other shells besides bash, as not all shells support the > and >> operators
echo "hello world" | sudo tee -a output.txt
This thread has good answers about tee
Use the >> operator to append text to a file.
I often confuse the two. Better to remember through their output:
> for Overwrite
$ touch someFile.txt $ echo ">" > someFile.txt $ cat someFile.txt > $ echo ">" > someFile.txt $ cat someFile.txt >
>> for Append
$ echo ">" > someFile.txt $ cat someFile.txt > $ echo ">" >> someFile.txt $ cat someFile.txt >>
this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.
Run the above with the cron every hour, or
while : do cmd >> o.txt && [[ $(wc -l
I would use printf instead of echo because it's more reliable and processes formatting such as new line \n properly.
This example produces an output similar to echo in previous examples:
printf "hello world" >> read.txt cat read.txt hello world
However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent
printf "hello\nworld" >> read.txt cat read.txt hello world
I'd suggest you do two things:
- Use >> in your shell script to append contents to particular file. The filename can be fixed or using some pattern.
- Setup a hourly cronjob to trigger the shell script
For example your file contains :
1. mangesh@001:~$ cat output.txt 1 2 EOF
if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'
2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 1 2 EOF somthing to append
And to overwrite contents of file :
3. mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx somthing new to write
This is misleading in many details. Spaces are not important and piping an empty output to cat is . just completely wacky. (It's empty because you just redirected standard output to a file.)
In Linux, You can use cat command to append file content to another file
In the previous command you will append content of fileName_1.txt to fileName_2.txt .
In Windows OS you can use type command
type fileName_1.txt >> fileName_2.txt
While all of these answers are technically correct that appending to a file with >> is generally the way to go, note that if you use this in a loop when for example parsing/processing a file and append each line to the resulting file, this might be much slower then you would expect.
A faster alternative might be this:
stringBuilder="" while read -r line; do # $'\n' prints a newline so we don't have to know what special chars the string contains stringBuilder+="$line"$'\n' done < "myFile.txt" echo "$stringBuilder" >$file
WARNING: you are reading all lines into memory; memory is a limited resource, so don't go doing this for gigantic files.