How to count the number of lines in a text file starting with a certain word?
I do not want to use sed
and then wc -l
. Any better solution?
How do I count lines if given word or string matches for each input file under Linux or UNIX-like operating systems? You need to pass the -c or --count option to suppress normal output. It will display a count of matching lines for each input file.
Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.
The wc command stands for “word count” and has a quite simple syntax. It allows you to count the number of lines, words, bytes, and characters in one or multiple text files.
This uses the -o option of grep, which prints every match in a separate line (and nothing else) and then wc -l to count the lines.
Just grep your word and then use wc -l to count the lines... like thisgrep '^your_word' /path/to/file | wc -l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With