Split header and footer into separate files using awk

Recently I had to write a shell script to read a file and split it into header and footer. The header and footer were to be saved into different files. At first I decided to write a script to loop through the file and save the content after performing the necessary condition check. But later I decided that this is not the best solution and checked whether there was a single line command for the same. As usual, I found a simple solution to the problem with awk.

awk '{if (NR == 1)print >> "header.txt"; else print >> "body.txt";}' input.txt
Where NR is a built-in variable that contains the number of the current record / line,
input.txt is the input file,
header.txt is output file for header,
body.txt is the output file for the remaining content

Awk reads the input file (input.txt) line by line and checks whether the current line is the first line. If so the content is appended ( >> ) to the file header.txt. Else the content is appended to body.txt.

By Joyce

I am a co-founder and director of Ennexa Technologies. To know more about me, visit my about page. You can find a list of websites maintained by our company at the links page.