131

How would I calculate and display the number of lines and words that are contained in a .sh file?

0

4 Answers 4

162

Use the program wc.

  • To count the number of lines: -l

      wc -l myfile.sh
    
  • To count the number of words: -w

      wc -w myfile.sh
    

See man wc for more options.

1
  • 3
    Be aware that the documentation says: "print the newline counts" when using the -l option, so if your file have three lines (two \n), thus, wc -l myfile.sh will return 2. Feb 17, 2022 at 14:36
31

As mentioned by souravc, you can use wc for this:

$ wc -w statusToFiles.sh 
10 statusToFiles.sh
$ wc -l statusToFiles.sh 
6 statusToFiles.sh

To only display the count itself, you can pipe that output to awk, like this:

$ wc -l statusToFiles.sh | awk '{ print $1 }'
6

...or as kos mentioned below:

$ < statusToFiles.sh wc -l
6
0
21

You can use grep command with blank matching string

grep "" -c file_path
5
  • 2
    Why does this is answer not have more upvotes? Is there something fishy about it? It works like a charm for me and the code looks very simple. Nov 2, 2019 at 11:04
  • 1
    or with non-blank matching string if you want to count non-empty lines grep -c . file (The period . matches any single character.)
    – jakun
    May 29, 2020 at 16:01
  • 1
    @FelixCrazzolara because the wc -l command is three times faster
    – Hannibal
    Aug 26, 2022 at 20:06
  • 1
    @Hannibal but grep use frequently and easy to remember
    – andreykyz
    Sep 2, 2022 at 15:04
  • This worked for me as I was not able to use wc Sep 26, 2023 at 20:57
8

You can also output the entire file with line numbers in front of every line using the command below:

cat -n myfile 
1
  • This is useless for big files (e.g. 250MB), instead it may causing freeze Jun 29, 2020 at 12:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .