parse a file for a special character

hello,

How to parse a file to see if a specific line is commented by '#' character?

filename: file1

cat file1

...
# /usr/bin/whatever
...

thank you

What do you want if it's commented out? The line itself? The line number?...

I'd suggest

man grep

or maybe have a look into awk, if you need more features.

I am looking for this:

when /usr/bin/whatever is commented, echo something
if it is not commented, echo something else.

thanks

Could you please be more specific about your question ?

Something like this ?

awk '{ if ( match($0, "^#") ) { print "line is commented" } else { print "line is not commented" } }' filename

Or, if you want to test only the lines containing /usr/bin/whatever, you can modify the very good suggestion above:

awk '$0 ~ /\/usr/bin\/whatever/ { if ( match($0, "^#") ) { print "line is commented" } else { print "line is not commented" } }' filename

Awk is pretty fantastic for this sort of thing.

I think OP gave the above as an example.

But still, what you gave is a good suggestion :slight_smile:

Check some entry commented not or not
grep -n "$entry_name" "$file_name" | awk '$2~/^#/{print $2, "Line", $1"is commented"}'
Check some line commented or not
awk '$0 ~/^#/{if( NR == "$line_num" ) printf("commented: 5d\n", NR);}

What if there are multiple /usr/bin/whatever lines?

The awk line will find all of them. It starts at the top of the file, finds each line containing the string "/usr/bin/whatever" (without quotes), and for each one found, it evaluates whether it has # in front. Multiple lines aren't a problem.

Hi all again

On a Solaris machine:

#awk '$0 ~ /\/usr/bin\/whatever/ { if ( match($0, "^#") ) { print "line is commented" } else { print "line is not commented" } }' filename

awk: syntax error near line 1
awk: bailing out near line 1

On a Redhat machine:

awk '$0 ~ /\/usr/bin\/whatever/ { if ( match($0, "^#") ) { print "line is commented" } else { print "line is not commented" } }' filename
awk: cmd. line:1: $0 ~ /\/usr/sbin\/whatever/ { if ( match($0, "^#") ) { print "line is commented" } else { print "line is not commented" } }
awk: cmd. line:1: ^ backslash not last character on line

any idea?

thank you,