1

I saw this question: count (non-blank) lines-of-code in bash

I understand this pattern is correct.

grep -vc ^$ filename

Why this pattern returns same result?

grep -c '[^ ]' filename

What is trick in '[^ ]'?

  • `grep -c '[^ ]'` counts any line that has a non-space character. For example, `foo 123` will be counted since alphabets are not a space character. So, which one to use depends on whether a line containing only space characters should be counted or not. – Sundeep Jul 31 '21 at 07:51
  • Thanks for a comment. I think your comment is enough as an answer. I want to approval, can you write as an answer? –  Jul 31 '21 at 08:07

1 Answers1

0
$ printf 'foo 123\n  \nxyz\n\t\n' > ip.txt
$ cat -T ip.txt
foo 123
  
xyz
^I

$ grep -vc '^$' ip.txt
4
$ grep -c '[^ ]' ip.txt
3
$ grep -c '[^[:blank:]]' ip.txt
2

grep -c '[^ ]' counts any line that has a non-space character. For example, foo 123 will be counted since alphabets are not space characters. So, which one to use depends on whether a line containing only space characters should be counted or not.

Sundeep
  • 23,246
  • 2
  • 28
  • 103