Sometimes you may need to append text at end of each line in Linux. For example, you may want to append a new line character or some other string at the end of each line in a file. Although >> and tee operators allow you to append text at the end of file, they cannot be used to append text at the end of each line. For this purpose, you will need to use the sed command in Linux. sed is a powerful Linux command that allows you to perform numerous operations on strings & texts. In this article, we will look at how to append text at the end of each line in Linux.
How to Append Text At End of Each Line in Linux
Let us say you have the following file data.txt with IP addresses as shown below.
127.0.0.1 192.0.0.1 243.23.43.1
And you want to add :80 to each line to include port numbers too.
127.0.0.1:80 192.0.0.1:80 243.23.43.1:80
For this purpose, you can use the following sed command.
$ sed -i s/$/:80/ data.txt
The above command will add :80 to each line of your file. Here is the explanation of our sed command.
- -i – edit file in place
- s – for substitution
- / – substitution based on regular expressions
- $ – regular expression to match the end of line
- :80 – text to add at the end of every line
The above sed command matches end of line for each line, using $ character and adds the text “:80” to each line. The s/// finds the end of each line of your file, using $ character, and appends :80 to it.
If you don’t want to modify the input file, but want to save the output to another file, then use the redirection (>) operator as shown below. In the following command, we save the modified text in a data-new.txt file.
$ sed -i s/$/:80/ data.txt > data-new.txt
You can modify the above command as per your requirement. If you want to automate the appending of text then you can even use it in a shell script or run it as a cron job.
Here is an example of shell script that accepts the file name to be modified as 1st argument and the string to be appended as second argument. Create an empty shell script file as shown below.
$ sudo vi line_append.sh
Add the following lines to it.
#!/bin/sh sed -i "s/$/$2/" $1
Save and close the file. Please note, we are using shell variable $2 in substitution expression, so we need to enclose it in double quotes “s/$/$2”. This way, when you run shell script, $2 will be replaced by second command line argument.
Make the shell script executable.
$ sudo chmod +x line_append.sh
You can run the shell script as shown below.
$ ./line_append.sh data.txt :80
In this article, we have learnt how to append text to the end of each line in text file. You can modify the commands and shell script as per your requirements.