简体   繁体   English

使用单个变量传递对awk中多个字段变量的引用?

[英]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. 我想将对任意多个字段变量的引用传递到awk中,并使其在不使用for循环的情况下为每一行打印出每个变量的值。

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." 我想要一个“ aa:cc:dd”的输出。 When I try it as-is, I get an output of $1":"$3":"$4. 当我按原样尝试时,得到的输出为$ 1“:” $ 3“:” $ 4。 Is it possible to do this for any number of field variables in var without doing a for loop? 是否可以在不执行for循环的情况下对var中的任何数量的字段变量执行此操作?

No it's not possible to do in awk with out looping but you could do it with cut : 不,不可能在awk中进行循环而不是循环,但是您可以使用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 这会将您想要的变量作为文字awk打印格式传递,即

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

You can utilize system function of awk to achieve this: 您可以利用awk的系统功能来实现此目的:

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

OUTPUT: 输出:

aa:cc:dd 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. 我仍然不建议这样做,因为可能仍有$ var的某些值使您失望。 Just pass in the field numbers you want and use a loop to print those fields 只需传递您想要的字段编号并使用循环来打印这些字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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