
Counting commented lines (full-line comments only)
Quote:
> > awk 'BEGIN {kount=0} \
> > /^[ \t]*\|.*/ { kount++ } \
> > END {print "count of comments = " kount } ' <filename>
> You shouldn't have to search for tabs explicitly as you are doing now.
> In fact, the way your code is written, you must have a tab in order to
> get a "hit".
Huh?! Sridhar's regular expression correctly matches a record (i.e.,
a line) that begins with zero or more space or tab characters followed
by a vertical bar. (His use of .* unnecessarily matches the rest of
the string and has no impact on the success or failure of the match.)
This regular expression does not require a tab anywhere in the record
for a successful match.
Quote:
> By default, awk uses tabs and spaces as field seperators and so
> basically ignores them.
This is false. An awk regular expression pattern never arbitrarily
ignores anything. The class of characters awk uses as the default
field separator is immaterial here as this script doesn't use fields
($1, $2, ..., $NF).
Quote:
> Your code could be:
> awk '/^\|/ {++kount}; END {print "count of comments = " kount}' <fname>
It could be, but it wouldn't be correct for his application. This script
counts only those lines in which the first character is a vertical bar.
Sridhar clearly defined what he wants to count:
I want to count full-line comments in a program. In my case,
a comment is a line or a part of line which starts with "|" (similar
to // syntax in C++).
[...]
DETAILS:
My input could be as follows :
| compare values and do something ...
if ... then |* is x = y ?!
....
endif
|* half-commentt .. .
|* one more comment . . .
|----------- functions -----------
<more statements .... >
In this particular example, my output
must be 4.
Quote:
> To count every line with a | character and therefore presumably
> all comments in a file:
> awk '/\|/ {++kount}; END {print "count of comments = " kount}' <fname>
This certainly counts all comments in a file, but it also incorrectly
counts each of the following lines:
foobar ~ /foo|bar/
if (foo || bar)
print "a vertical bar: |"
foo++ |* increment the foo counter
In the last line above, the vertical bar begins a comment, but it is not
a "full-line comment" and, as such, is not a line that Sridhar wants to
count. (Op. cit.)
--
Jim Monty
Tempe, Arizona USA