Thursday, May 24, 2012

7 different ways to print the last line of a file in Linux

 In an earlier article, we saw the different ways in which we can print the first line of a file.  In this article, we will see the different ways in which we can print or display the last line or the trailer record of a file in Linux.

Let us consider a file with the following contents:
$ cat file
1. The tail is the most common command used. tail command prints the last part of the files. -1 specifies to print one line from the last part.
$ tail -1 file
2. The END label in awk makes it even more easily. END label is reached once the entire file is parsed. Hence, on reaching END, the special variable $0 will be holding the last line of the file.
$ awk 'END{print}' file
3. In sed, $ indicates the last line, and $p tells to print(p) the last line($) only.
$ sed -n '$p' file
4. Another option in sed is to delete(d) all the lines other than(!) the last line($) which in turn prints only the last line.
$ sed '$!d' file
5. In perl, every line being processed is saved in a variable. Same explanation as of awk. Only difference here is the scope of the variable $_ is only present in main, not in the END label. Hence, every line is stored in a variable and the same variable is used in the END.
$ perl -ne '$x=$_;END{print $x;}' file
6. tac command prints a file in reverse. By printing the first line of the tac output using the head, we will get the last line of the file printed. Not the best of options, but an option nevertheless.
$ tac file | head -1
7. Solution using a proper shell script.  The file is processed using the while loop where each line is read in one iteration. The line is assigned to a variable x, and outside the loop, x is printed which will contain the last line of the file.

while read line
done < file
echo $x
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment