user1382685
user1382685

Reputation: 49

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?

Upvotes: 0

Views: 769

Answers (5)

Ed Morton
Ed Morton

Reputation: 203924

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

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85845

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

Upvotes: 1

anubhava
anubhava

Reputation: 785471

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

Upvotes: 0

parkydr
parkydr

Reputation: 7782

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

This will pass the variables you want as literal awk print format i.e

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

Upvotes: 0

Kent
Kent

Reputation: 195169

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

Upvotes: 0

Related Questions