Lee Ikard
Lee Ikard

Reputation: 76

Count how many times a line appears based on part of text in a file with bash

Lets say I have a file:

Player spawned prop
'player' has left the server
'newplayer' has connected
'someone else' has connected

I want to count how many times the string 'has connected' appears, to get a final number of 2.

Upvotes: 0

Views: 669

Answers (2)

Adam M. Erickson
Adam M. Erickson

Reputation: 68

If you do a search for "shell script" and "count string". You should find

https://unix.stackexchange.com/questions/6979/count-total-number-of-occurrences-using-grep

will help you find a lot of ways you can do it.

Grep pipped to a word count is the easiest way, no need to complicate it with regex for a static string.

Upvotes: 0

sjsam
sjsam

Reputation: 21965

 grep -o 'has connected' file| wc -l

should do it.

grep manpage says :

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

wc manpage says :

-l, --lines
print the newline counts

Upvotes: 1

Related Questions