Awk to take two variables as parameters and return a value
I have a file with 50 lines. Each row has three columns. The first two columns are variables and this will be passed as parameters to return the value of the third column. for ex .. The command_file.txt file is a file and contains
AB 10 CD 20 EF 30 GH 50 IJ 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 the value 10 to be returned. But it returned errors. But if I hard-code the value in the command below it works.
GET_VALUE=`awk '/A B'/ $READ_FILE lawk '{print $3}'`
Any suggestions? Thank.
source to share
You need to use a variable awk's
before the awk script starts avoiding hairy quoting, and also 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
source to share
Sorry that I cannot determine what your script is trying to do, so I cannot debug it properly. I think maybe you have nested quotes or something else 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
Ok, thanks to others for pointing out what you are trying to do with the -v options.
The code is missing the command $ echo GET_VALUE, and instead of the letter l instead of the letter l. Besides, there are other typos as well.
I think it 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 doesn't require extra effort to pass command line variables to awk.
source to share
I know this is an old post, but awk is even older and still in use and people are still looking for the same answers. I believe I was an example of this.
I decided to implement a similar scenario, but would like to get the predefined variables in the config file. The user passes the partial name of the config file to the script as the first parameter.
cfg=$PWD/$1.cfg
foo=$(awk '$1 ~ /foo/ { print $2 }' $cfg)
source to share