count number of lines in terminal output

BashTerminal

Bash Problem Overview


couldn't find this on SO. I ran the following command in the terminal:

>> grep -Rl "curl" ./

and this displays the list of files where the keyword curl occurs. I want to count the number of files. First way I can think of, is to count the number of lines in the output that came in the terminal. How can I do that?

Bash Solutions


Solution 1 - Bash

Pipe the result to wc using the -l (line count) switch:

grep -Rl "curl" ./ | wc -l

Solution 2 - Bash

Putting the comment of EaterOfCode here as an answer.

> grep itself also has the -c flag which just returns the count

So the command and output could look like this.

$ grep -Rl "curl" ./ -c
24

EDIT:

Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l is much more useful as you can use it with other programs than grep as well.

Solution 3 - Bash

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

Solution 4 - Bash

"abcd4yyyy" | grep 4 -c gives the count as 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionroopunkView Question on Stackoverflow
Solution 1 - BashJoão SilvaView Answer on Stackoverflow
Solution 2 - BashJelteFView Answer on Stackoverflow
Solution 3 - BashGCSView Answer on Stackoverflow
Solution 4 - BashshivaView Answer on Stackoverflow