Hi everyone,
The following piece of awk code works fine if I use eval builtin
var='$1,$2'
ps | eval "awk '{print $var}'"
But when I try to knock off eval and use awk variable as substitute then I am not getting the expected result
ps | awk -v v1=$var '{print v1}' # output is $1,$2
ps | awk -v v1=`echo $var` '{print v1}' # output is same as above
ps | awk -v v1=$var '{print $v1}' # output is all the fields of ps command
ps | eval "awk -v v1=$var '{print v1}'" # output is column of comma
How to get the desire output without using eval?
The shell substitutes variables in "quotes".
var="$1,$2"
But here you maybe want
var='$1,$2'
ps | awk '{print '"$var"'}'
?
Brilliant MadeInGermany !! Also, could you please help me to how to use awk variable in this scenario?
The $1,$2
is a piece of awk code.
You cannot run a string (as assigned to an awk variable) as awk code.
(Unless there were an eval
built into awk.)
This following awk code interprets a given string as you intend:
var='1,2'
ps | awk -v v1="$var" 'BEGIN{n=split(v1,a,",")} {for(i=1;i<=n;i++) printf "%s\t",$(a); print ""}'
1 Like
Jotne
November 18, 2013, 5:28am
5
This works.
ps | awk "{print $var}"
Single quote does not expand variable.
1 Like