Question

I am having a little trouble with using a variable and printing the 2nd field with the awk command. I am attempting to grab a number from a value in a file. The value in the file looks like

MAX=10000 (I want the Number only), I am passing this into a variable in a script so in the script I have variables

parm_file=ParmFiles/Parmfile.parm
session=s_session_value

OLD_MAX_SEQ_NR=`awk -F '=' "/$session/ {getline; print $2}" < $parm_file` 

because I have double quotes to identify the $session variable, it is taking the $2 as a variable too, and so it is just printing the whole line, instead of the second field.

I've tried also to pass the variable into the awk command like

OLD_MAX_SEQ_NR=`awk -F '=' \
    -v var="$session" \
    '/var/ {getline; print $2}' < $parm_file`

But it does not seem to be putting the variable where var is. I have even tried hard coding the -v var="s_session_value" and it does not work.

I can't figure out a way to make the command look at the $2 as it normally does instead of a variable. Any help would be greatly appreciated.

Was it helpful?

Solution

Try this:

parm_file=ParmFiles/Parmfile.parm
session=s_session_value

OLD_MAX_SEQ_NR=$(
    awk -F'=' -v pat="$session" \
        '$0 ~ pat {getline; print $2}' < "$parm_file"
) 
  • You need to pass shell variables to awk by defining an awk variable using -v.
  • Using variable inside /../ is taken as literal. So use $0~var_name construct.
  • Using back-ticks is deprecated. Use command substitution $(..)
  • Quote your variables.

OTHER TIPS

It's a bit tricky without a sample line of the parm file. But I don't understand why you don't use cut, it makes it much easier?

OLD_MAX_SEQ_NR=$(grep "$session" "$parm_file" | cut -d= -f2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top