I have a file which has 50 rows. Each row is made up of three columns. The first two columns are the variables and this will be passed as parameters to return the 3rd column's value. for ex.. command_file.txt is the file and it contains
A B 10 C D 20 E F 30 G H 50 I J 70 ...
I have a script with the following command.
#!/user/bin/sh READ_FILE=/export/home/user/command_file.txt VA1=A VA2=B GET_VALUE=`awk '/ -v var="$VA1" '$1 ~ var' -v var1="$VA2" '$1 ~ var1''/ $READ_FILE l awk '{print $3}'` echo $GET_VALUE
When I call this script passing A and B as parameters I expect a value of 10 to be returned.But it returned errors. But if I hard code the value on the below command it will work.
GET_VALUE=`awk '/A B'/ $READ_FILE lawk '{print $3}'`
Any suggestions? Thanks.
You have to use awk's
variable passing before the awk script begins to avoid hairy quoting, plus fix other problems:
#!/user/bin/sh
READ_FILE=/export/home/user/command_file.txt
VA1=A
VA2=B
GET_VALUE=$(awk -v var="$VA1" -v var1="$VA2" '$1 ~ var && $2 ~ var1 {print $3}' $READ_FILE)
echo $GET_VALUE
I apologize that I can't really determine what your script is trying to do, so I can't debug it properly. I think maybe you have nested quotes or something else is going on.
I think the one-liner below will do what you want.
#!/bin/bash
grep "^$1 $2" /export/home/user/command_file.txt | awk '{print $3}'
Edit
Okay thanks to others for pointing out what you were trying to do with the -v options.
Your code is missing a $ on the echo GET_VALUE command, and you have a letter l instead of a pipe |. Plus there are other typos as well.
I think this works
READ_FILE=/export/home/user/command_file.txt
awk -v var1=$1 -v var2=$2 '$1 ~ var1 && $2 ~ var2; /^var1 var2/' $READ_FILE | awk '{print $3}'
but I prefer the grep command above as it requires no extra effort to pass the command line variables to awk.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With