How to Count the Number of Lines in a File in a Shell Script


A shell script is a program that is interpreted by the Linux or Unix system shell. It uses both operating system and shell commands to perform the actions needed. You can provide the name of the file that you want to evaluate at the command line. This allows use of the same script on multiple files without having to change any portion of it. The "wc" command can function to count the number of lines within a file.

  • Open a blank plain text document in any text editor.

  • Type the line


    to start the shell script.

  • Type the line

    num= wc -l $1 | awk '{print $1}'

    to count the number of lines in the file specified at the command line and place the value in the "num" variable.

  • Type the line

    echo $num

    to print the number of lines to the screen.

  • Save the file as "".

  • Open a terminal window.

  • Type the command "chmod +x" to make the script executable.

  • Type the command " filename.txt" to execute the script. Replace "filename.txt" with the file you want to count.

Related Searches


Promoted By Zergnet


Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!