I have the following bash script segment that uses grep to find out whether input line contains certain pattern or not.
echo $input_line | grep -q "$pattern"
if [ $? -eq 0 ];
then
# Input line contains pattern
# Execute some bash commands
else
# Input line DOES NOT contain pattern
# Execute other bash commands
fi
I need to rewrite it with awk without grep. I tried several variants, but none of them works, for example, both of the following always print MATCH, no matter contains input line pattern or not.
echo $input_line | awk -v b="$pattern" '/pattern/ { print "MATCH" }'
echo $input_line | awk -v b="$pattern" '/$0 ~ pattern/ { print "MATCH" }'
Update:
Removing / as recommended resolved the described issue. Now I have the problem with returning result of awk command for usage in if statement. I wrote the following "ugly" snippet:
pattern="abc"
input_line="xyz123 678q we uqa abc asd"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
echo Input line $input_line contains pattern $pattern
else
echo Input line $input_line DOES NOT contains pattern $pattern
fi
input_line="tult uil7665 5444tu l098 7tu"
RES=$(echo $input_line | awk -v pat="$pattern" '$0 ~ pat { print "1" }')
if [ $RES -eq 1 ];
then
echo Input line $input_line contains pattern $pattern
else
echo Input line $input_line DOES NOT contains pattern $pattern
fi
So I've got the following output, because in second case when input line doesn't contain pattern the variable RES is not set:
Input line xyz123 678q we uqa abc asd contains pattern abc
./test.sh: line 21: [: -eq: unary operator expected
Input line tult uil7665 5444tu l098 7tu DOES NOT contains pattern abc
Any ideas how to improve this "ugly" script snippet with if statement?
Thanks