To know about how many lines exist in file is important for System Admin.There are sometimes very huge files which has lot of line numbers hence it is not advisable to open the file using cat command or any file editor like vi,vim,nano etc., because it takes lot of time to open it. Hence it is important to check how many lines exist in file.
In this post we will know 4 linux commands through which you can get number of lines in file. Most popular command is wc -l filename.In other words you can also say 3 other alternate method of wc -l filename command

4 Linux commands to get number of lines in file

(1) wc command: wc command can be used with different switches to get different output.To get the number of lines in file,we use the switch -l

Syntax: wc -l filename

Example:

linux@tuxworld:/tmp$ wc -l test 
25 test
linux@tuxworld:/tmp$

(2) awk command: awk is pattern scanning and processing language and with the help of many arguments it is widely use in command line. One of the example with awk command is to get number of lines in file

Syntax: awk 'END { print NR }' filename

Example:

linux@tuxworld:/tmp$ awk 'END { print NR }' test
25
linux@tuxworld:/tmp$

(3) sed command: Another powerful command sed, it is stream editor for filtering and transforming text.By using some arguments with sed command we can also find out number of lines in file.

Syntax: sed -n '$=' filename

Example:

linux@tuxworld:/tmp$ sed -n '$=' test 
25
linux@tuxworld:/tmp$

(4) mapfile command: The bash builtin mapfile reads from standard input and copies lines to the given array. By this method we can also get to know number of lines in file

Example:

linux@tuxworld:/tmp$ mapfile i < test
linux@tuxworld:/tmp$ echo "${#i[@]}"
25
linux@tuxworld:/tmp$ 
linux@tuxworld:/tmp$ unset i

Note: "unset i" will unset the value of variable called i which we have used in command mapfile in above given example.

Read Some More Articles

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.