How to add header and trailer line to a file in Linux

In this article, we will see the different ways to add a header record or a trailer record to a file.

Let us consider a file, file1.

$ cat file1
apple
orange
grapes
banana

Adding a line to the start of the file (header)

1. To add a header record using sed:

$ sed '1i some text at the beginning' file1
some text at the beginning
apple
orange
grapes
banana

The ‘1i’ in sed includes(i) the line some text at the beginning only before the first line(1) of the file. The above command displays the file contents along with the header without updating the file. To update the original file itself, use the -i option of sed as shown below:

$ sed -i.bkp '1i some text at the beginning' file1

The -i.bkp option create a backup file named file1.bkp before doing any changes to original file. The extension .bkp can be anything of your choice.

2. You can also use this example of sed to insert a header line:

$ sed '1s/^/some text at the beginning\n/' file1

The ‘1’ indicates the line number that will only be matched while doing the substitution with ‘s’ command. ‘^’ symbol indicates the start of the line. Also note the carriage return ‘\n’ added at the end, which helps to print a new line after the replacement.

3. You can also use the cat command with bash printf statement to add a line at the start of the file.

$ printf '%b' 'some text at the beginning\n' | cat - file1

4. To add a header record to a file using awk:

$ awk 'BEGIN{print "some text at the beginning"}1' file1
some text at the beginning
apple
orange
grapes
banana

The BEGIN statement in awk makes the statement some text at the beginning to get printed before processing the file, and hence the header appears in the output. The 1 is to indicate to print every line of the file.

Adding a line to the end of the file (trailer)

1. Easiest of all commands here is simple using the redirection to append a line at the end of the file. For example:

$ echo "some text at the end" >> file1

2. To add a trailer record to a file using sed:

$ sed '$a some text at the end' file1
apple
orange
grapes
banana
some text at the end

The $a makes the sed to append(a) the statement some text at the end only after the last line($) of the file.

3. To add a trailer record to a file using awk:

$ awk '1;END{print "some text at the end"}' file
apple
orange
grapes
banana
some text at the end

The END label makes the print statement to print only after the file has been processed. The 1 is to print every line. 1 actually means true.

sed on MAC OSX

sed behaves little different on MAC OS, as compared to the GNU sed. You may try below sed example for adding header line to the file in MAC.

$ sed -i '.bak' '1s/^/some text at the beginning\'$'\n/g' file1
Related Post