We help IT Professionals succeed at work.

condition check in awk

radix655
radix655 used Ask the Experts™
on
In Shell script.
I need to check if a value is equal to any of 500 different values. How do I do that?
I know all the 500 values before-hand. They are static
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2013
Top Expert 2013

Commented:
Assuming that you have those 500 values in a file, one per line:

CHECK=value
CHECKFILE=/path/to/inputfile

while read value; do
  [[ $value -eq $CHECK ]] && echo $CHECK found in $CHECKFILE
done < $CHECKFILE

Or with awk


CHECK=value
CHECKFILE=/path/to/inputfile
awk '{if ($1=='$CHECK') print "'$CHECK' found in $FILENAME}' $CHECKFILE

wmp
Most Valuable Expert 2013
Top Expert 2013
Commented:
Sorry, one wrong $ character:

CHECK=value
CHECKFILE=/path/to/inputfile
awk '{if ($1=='$CHECK') print "'$CHECK' found in FILENAME}' $CHECKFILE

wmp
or just

if grep "^${CHECK}$" $CHECKFILE >/dev/null
then
  : found it
fi
Gerwin Jansen, EE MVETopic Advisor
Most Valuable Expert 2016
Commented:
There are a few ways you can do this, you could create a text file (test.txt) that contains your values and create a script that takes 1 parameter that finds your value in the text file.

script: (gr.sh)
grep -q $1 test.txt
if [ $? -eq 0 ]
then echo "Value $1 found"
else echo "Value $1 not found"
fi

Open in new window

test.txt:
1
2
3
5
6

Open in new window

test with '4':
./gr.sh 4
Value 4 not found

Open in new window

test with '6':
./gr.sh 6
Value 6 found

Open in new window

From earlier questions you have asked, do you need to do this as part of a larger awk script?

If so, something like this, where myval is the awk variable containing the value you are checking, and filelist is the name of the external file containing the matches.  

   rc=system("grep -q ^" myval "$ filelist");
     
rc will then be 0 if the exact value is found in the file, and 1 if it isn't.

Author

Commented:
Thank you all.

@simon. I thought I would do this in awk but after seeing your grep solution I thought that is better. Thanks for system() function. I didn't know that.

I am doing like this. So, I don't have to get the variable in awk and compare. Thanks.

REGEX=`awk '{ print $1 ; }' include_list.log`
cat $file | grep "${REGEX}" | awk -f get_count.awk

Author

Commented:
My include_list.log has something like (val1|val2|val3...val500)
Most Valuable Expert 2013
Top Expert 2013

Commented:
awk -F"|" -v VAL=$myvalue '{for(i=1;i<=NF;i++) {if($i == VAL) print VAL, "found!"}}' include_list.log