Trouble with awk command

Hi,

I need to read a string with ; separated using loop one filed by one field and perform some operation. Can you please check and let me know how to print command parameterised.

key=phani;ravi;kiran
number_of_keys=`echo $key|awk '{print NF}' FS=';'`
for (( i = 1; i <= $number_of_keys; i++ ));
do
key=`echo $KEY_TO_COMPARE|awk 'BEGIN { FS = ";" } ; {print $i}'`
cat /home/t.txt| grep -i $key >> temp.txt
done

content of /home/t.txt

a ais bad
phani is good
kiran is bad
people
bye

modified your code
try

key="phani;ravi;kiran"
number_of_keys=$(echo $key|awk '{print NF}' FS=';')
for (( i = 1; i <= $number_of_keys; i++ ));
do
key=$(echo $KEY_TO_COMPARE|awk -v var=i 'BEGIN { FS = ";" } ; {print $var}')
grep -i $key /home/t.txt >> temp.txt
done
1 Like

Or

key="phani;ravi;kiran"
echo $key | tr ';' '\n' > keys.lst
grep -if keys.lst /home/t.txt > temp.txt 

hope this helps :slight_smile:

1 Like

Use parameter substitution instead. Assuming there are no blank space separated values in key :

key="phani;ravi;kiran"

for k in ${key//;/ }
do
        grep -i "$k" /home/t.txt
done > temp.txt
1 Like
grep -if <(IFS=\;; printf "%s\n" $key) file
1 Like