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

Save

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

    !/bin/bash

    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 "count_lines.sh".

  • Open a terminal window.

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

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

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

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

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