Monday, June 21, 2010

5 different ways to count the total lines in a file



 In one of our earlier articles, we saw the different ways to find the length of a variable. In the same lines, we will see the different ways to get the count of total lines in a file.


1. The most common method used is the piping of wc command with cat.
# cat file | wc -l
2. grep has the '-c' option to do line count of patterns matched. The '.*' tells to match anything which essentially means to match every line.


# grep -c '.*' file
3.  sed uses '=' operator for line numbering. The '$' tells to give the count only for the last line.
# sed -n '$=' file
4. awk can be used to get the file count using NR variable. NR contains the line number and   by printing NR at the end block, we get the line number of the last line, which essentially is the total lines in a file.
# awk 'END {print NR}' file
5. perl also has the same END block like awk. However, $. denotes line number in perl.
# perl -lne 'END {print $.}' file
Related Posts Plugin for WordPress, Blogger...

2 comments:

  1. Example # 1 is an UUC

    should be

    wc -l file

    ReplyDelete
  2. 1. For normal files,
    wc -l
    2. For compressed files (.gz),
    zcat | wc -l

    ReplyDelete