Count letters 'a' from a file, using egrep and wc

Asked

Viewed 113 times

3

I’m doing a directed study on operating systems, and I’ve stalled on that question:

4) Using the egrep programme in conjunction with the programme wc, tell how many letters "a" there are in the messages.txt file .

I thought it was this way:

egrep "a" mensagens.txt | wc -c

but it is not, if anyone can help me I will be very grateful.

1 answer

4


Use the parameter to egrep -o which, according to man:

Prints only the matching part of the lines.

It will print only the part that fits the pattern described by you. This also solves the problem that if a pattern appears multiple times on the same line, the result of grep being only one line. That is, using this parameter, the grep command will output one line for each match, and these lines will contain nothing but the match itself.

Concatenating with the wc, we use the parameter -l, that according to man:

The number of lines in each input file is written to the standard output.

Simply count the number of lines in the input.

Final command:

egrep -o "a" mensagens.txt | wc -l

  • vlw, it was right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.