Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

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.

share|improve this answer
    
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. –  Paddy Landau Oct 1 '13 at 10:55
    
@PaddyLandau Thanks for spotting the typo! I've fixed it now. –  gniourf_gniourf Oct 1 '13 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? –  Paddy Landau Oct 2 '13 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.). –  gniourf_gniourf Oct 2 '13 at 17:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.