problem with printing out variable in awk

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!

  1. The problem statement, all variables and given/known data:

couldn't print out stored variable in awk

  1. Relevant commands, code, scripts, algorithms:

i have in a foreach loop:

set num=`blah blah`
if ( $num != "0" ) then
echo $x | awk 'BEGIN { FS="." } { printf "%s %s %s\n", $1, $0, num }'
else return
endif
end

im wondering why awk just couldnt print 'num' :confused:

  1. The attempts at a solution (include all code and scripts):

the above

  1. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):

Uni of Southampton, so on
Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

You don't get shell variables outside of the shell, and awk is not a shell extension. awk is its own, independent, self-contained language.

If you want to insert a variable into awk, you can do so with -v:

awk -v var="$var" ...
1 Like

so is that when i assign a variable (say 'num') some value outside awk, and then assign num to a variable in awk (say 'var' ) in this way:

awk -v 'BEGIN { FS="." } var="$num" { printf "%s %s %s\n", $1, $0, var }' 

like this?

No, like I showed you:

awk -v var="$var" ...

Where the ... is everything else you were putting into awk.

awk -v num="$num" 'BEGIN { FS="." } { printf "%s %s %s\n", $1, $0, num }'
1 Like

thanks for being helpful, anyway just found out that num=$num should work :smiley:

awk -v num="$num" is the preferred way, awk -v num=$num will break if $num contains spaces or certain special characters (this is not a shell assignment) ...