Monday, March 28, 2011

Different ways to add header and trailer line to a file



   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


1. To add a header record using sed:
$ sed '1i FRUITS' file1
FRUITS
apple
orange
grapes
banana
   The '1i' in sed includes(i) the line FRUITS 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.

2. To add a header record to a file using awk:
$ awk 'BEGIN{print "FRUITS"}1' file1
FRUITS
apple
orange
grapes
banana
  The BEGIN statement in awk makes the statement FRUITS 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.

3. To add a trailer record to a file using sed:
$ sed '$a END OF FRUITS' file1
apple
orange
grapes
banana
END OF FRUITS
  The $a makes the sed to append(a) the statement END OF FRUITS only after the last line($) of the file.

4. To add a trailer record to a file using awk:
$ awk '1;END{print "END OF FRUITS"}' file
apple
orange
grapes
banana
END OF FRUITS
   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.

4 comments:

  1. will it work in ksh? adding header record using sed. i got the error msg - Function i1 HEADER cannot be parsed.

    ReplyDelete