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 bananaThe '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' file1FRUITSappleorangegrapesbanana
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 appleThe $a makes the sed to append(a) the statement END OF FRUITS only after the last line($) of the file.orangegrapesbananaEND OF FRUITS
4. To add a trailer record to a file using awk:
$ awk '1;END{print "END OF FRUITS"}' fileThe 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.appleorangegrapesbananaEND OF FRUITS
very good one
ReplyDeletewill it work in ksh? adding header record using sed. i got the error msg - Function i1 HEADER cannot be parsed.
ReplyDeleteit should work in ksh as well..
ReplyDeleteNot working in ksh
ReplyDelete