I need to check if 2 values exists in the file and if they are equal print 0.
output.txt:
------------
1 2 3 4 5 6
Inputs:
a=1
b=2
My pattern matching code works but I am trying to set a counter if both the pattern matches which does not work.If the count > 0 ,then I want to check if $a==$b
awk '/$a/ && /$b/' output.txt ##worked when executed alone
BEGIN { count=0;} {$0~/$a/&&/$b/} { count++; } END { print "Numbers matching =",count;}' output.txt ##Not working.always returns 1
Welcome to forums hope you will enjoy learning here. Please use code tags as per forum rules for Inputs/codes/commands which you are using into your post as per forum rules. Now coming to your post, $a will denote value of a variable but in awk it wouldn't work like that way, there is NO need of $ sign to get the value of variables here. An example for this is as follows.
awk -vvariable=10 'BEGIN{print variable}'
Output will be as follows.
10
Now for your requirement as far as I understood your requirement, you have 2 variables named a and b and if there value is present in file(Taking your sample file only, because if file has multiple lines then we need to be more specific about your requirement as you need to tell us either you need to check variable in whole file or line by line is fine.) and their own values are equal then print value 0 in output.
Because I have taken an example where values or variable a and b are same it will show output as follows.
0
If you have any doubts or your requirement is not meeting this solution, I would suggest you to show your sample input with all conditions with their expected output and your O.S details too, hope this helps you.
shell variables (your a and b ) are not available in awk per se. On top, single quoting prevents shell expansion. So it's difficult to believe that your first sample code worked.
In awk , /.../ is a regex constant; you can't have variables in there $0~/$a/ and /$b/ are equivalent (but would not work as expected!) {...} is an action, not a pattern (so {count++} will always be executed)
Try
awk -vA=$a -vB=$b '
$0 ~ A && $0 ~ B { count++}
END {print "Numbers matching =",count+0
}
' file
You'll still need to make sure there are no false positives (as "100" would match "1")