bashawk

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?


Solution

  • 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}