简体   繁体   中英

Using single variable to pass in reference to multiple field variables in awk?

I'd like to pass a reference to any number of field variables into awk and have it print out the value for each variable for each line without using a for loop.

For example, I'd like to do something like:

var=$1":"$3":"$4
echo "aa bb cc dd" | awk -v var=$var '{print var}'

I would like an output of "aa:cc:dd." When I try it as-is, I get an output of $1":"$3":"$4. Is it possible to do this for any number of field variables in var without doing a for loop?

No it's not possible to do in awk with out looping but you could do it with cut :

$ var='1,3,4' 
$ echo 'aa bb cc dd' | cut -d' ' --output-delimiter ':' -f "$var"
aa:cc:dd

you want to have this:

awk -v var="$var" '{n=split(var,a,":");
   for(i=1;i<=n;i++)s=s sprintf("%s",$a[i]) (i==n?"":" ");
   print s}' 

test with your example:

kent$  var="1:3:4"

kent$  echo "aa bb cc dd"|awk -v var="$var" '{n=split(var,a,":");for(i=1;i<=n;i++)s=s sprintf("%s",$a[i]) (i==n?"":" ");print s}' 
aa cc dd
var='$1":"$3":"$4'
echo "aa bb cc dd" | awk  "{print $var}"

This will pass the variables you want as literal awk print format ie

echo "aa bb cc dd" | awk {print $1":"$3":"$4}

You can utilize system function of awk to achieve this:

var='$1":"$3":"$4'
echo "aa bb cc dd" | awk -v var="$var" '{system("set -- " $0 "; echo " var)}'

OUTPUT:

aa:cc:dd

This is the most simple and robust way to do what you specifically asked for:

$ var='$1,$3,$4'

$ echo "aa\tbb\tcc\tdd" | awk -F'\t' -v OFS=":" '{print '"$var"'}'
aa:cc:dd

I still wouldn't particularly recommend doing it though as there's probably still some values of $var that would trip you up. Just pass in the field numbers you want and use a loop to print those fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM