grep expression behaving weird (unix/mac) while reading a conf file

39 views Asked by At

What's going wrong in below grep expression, appreciate any help.

$cat foo.txt

## not to be read
; this one too and next one also coz it has sapce
first_var= first_val
second_var=y
second_var=yes

Now when I run below grep on Mac/Linux

 grep "^[^#;].*[^[:space:]]\=[^[:space:]].*[^=]" foo.txt

I get below output

second_var=yes

whereas I was expecting

second_var=y
second_var=yes

what I am going wrong here?

3

There are 3 answers

2
The fourth bird On

In the part after the = you expect 2 characters, and you only have a single y

You could make the second part optional if it should end on any character except =

grep "^[^#;].*[^[:space:]]=[^[:space:]]\(.*[^=]\)\?" foo.txt  

Output

second_var=y
second_var=yes
0
Jean-Baptiste Yunès On
grep "^[^#;].*[^[:space:]]\=[^[:space:]][^=]*" foo.txt

works as it specifies that = must be followed by a sequence of chars excepted =:

second_var=y
second_var=yes
0
anubhava On

Provided grep solutions solve your problem though I suggest considering this awk solution for the sake of the simplicity and readability:

awk -F= 'NF==2 && !/^;|[[:space:]]=|=[[:space:]]/' file

second_var=y
second_var=yes