Monday, April 16, 2012

Different ways to print the first line of a file



 In one of our earlier articles, we saw how to add a header or a trailer record to a file.  Let us see in this article how to print the first line or the header record of a file. Assuming a file with the sample contents as shown below:
$ cat file
Unix
Linux
Solaris
1. The default command which comes to our mind is the head command. head with the option "-1" displays the first line.
$ head -1 file
Unix
2.  The best of all options since it uses an internal command. read command is used to take user input from the standard input in shell. It can also be used to read from a file.
$ read a < file
$ echo $a
Unix
    Usually, read is used inside a loop to read a file line by line. But, when used in the above way, read command reads only the first line of the file.

3. awk's special variable NR contains the line number of the record being processed.  Checking for NR for the line number prints that particular line of the file.
$ awk 'NR==1' file
Unix
4. Similar to awk's NR, perl's alternative is $. which has the line number.
$ perl -ne 'print if ($.==1);' file
Unix
5. The last is the sed command. The -n to suppress the default printing. 1p means to print only the first line.
$ sed -n '1p' file
Unix
     In the above approach, if the file being operated upon is a huge file, the sed command will be a problematic one. It is because even though only the first line is printed, still the sed parses the entire file.
$ sed -n '1p;1q' file
Unix
    This is the right way to use sed for this requirement. 1q means to quit after the first line. In other words, '1p;1q' means to print the first line and quit immediately which in turn prevents from parsing the entire file.

6. The more traditional while loop. The file is read inside the while loop and we exit after reading the first line. This also does not contain any external command.
$ while read a
> do
>   echo $a
>   break
> done < file
Unix

No comments:

Post a Comment