1

I have to count the number of lines that contains comma, apostrophe, or is a completely blank line.

I know to count the number of blank lines I would do egrep -xc '' filename

But I am not so sure how to do all of it at once, to also get the lines with apostrophe and comma also, as well as blank lines.

1 Answer 1

5

It seems you're doing your homework today...

A solution:

grep -c "\([',]\|^$\)" filename

If by blank line you also want to include those that contain only spaces:

grep -c "\([',]\|^[[:space:]]*$\)" filename

The trick for apostrophes is to use double quotes, otherwise ''' will be an error. The construct \( regexp1 \| regexp2 \) will match all lines that match either regexp1 or regexp2. The regexp [',] matches all lines that contain either a quote ' or a coma ,.

Here you need to escape the parentheses () and the pipe | otherwise grep tries to find these characters, and don't consider them as regexp constructs. If you don't like escaping these, you can use the -E switch (for Extended regexps) or egrep directly as:

grep -cE "([',]|^$)" filename

or

egrep -c "([',]|^$)" filename

In your OP you mention the -x switch. It works to get empty lines... but will not work with your coma/quote requirement. So to match a blank line I'm using ^$ (^ is an anchor for the beginning of line and $ is an anchor for the end of line).

Hope this helps.

4
  • There is no difference between solution 1 (without blanks) and solution 2 (with blanks). May I suggest that the second solution read grep -c "\([',]\|^ *$\)" filename or egrep -c "([',]|^ *$)" filename? Please correct me if this is wrong. Oct 1, 2013 at 10:55
  • @PaddyLandau Thanks for spotting the typo! I've fixed it now. Oct 1, 2013 at 17:34
  • Thanks for fixing it (and showing me how it should be done). I think that the same applies to the egrep examples, doesn't it? Oct 2, 2013 at 12:32
  • @PaddyLandau Yes, same applies for egrep: ^$ matches really empty line (no blanks), and ^[[:spaces:]]*$ matches empty lines (that may contain spaces, tabs, etc.). Oct 2, 2013 at 17:03

You must log in to answer this question.

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