将变量从 bash 传递到 awk
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16340775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing variables into awk from bash
提问by sodiumnitrate
I am writing a shell script file in which I have to print certain columns of a file. So I try to use awk. The column numbers are calculated in the script. Nprop is a variable in a for loop, that changes from 1 to 8.
我正在编写一个 shell 脚本文件,我必须在其中打印文件的某些列。所以我尝试使用awk。列号在脚本中计算。Nprop 是 for 循环中的一个变量,从 1 变为 8。
avg=1+3*$nprop
awk -v a=$avg '{print $a " " $a+1 " " $a+2}' $filename5 >> neig5.dat
I have tried the following also:
我也尝试了以下方法:
awk -v a=$avg '{print $a " " $(a+1) " " $(a+2) }' $filename5 >> neig5.dat
This results in printing the first three columns all the time.
这导致始终打印前三列。
采纳答案by Mat
avg=1+3*$nprop
This will set $avgto 1+3*4, literally, if $propis 4 for instance. You should be evaluating that expression:
这将设置$avg为1+3*4,字面上,$prop例如,如果是 4。您应该评估该表达式:
avg=$(( 1+3*$nprop ))
And use the version of the awkscript with parenthesis.
并使用awk带括号的脚本版本。
回答by Chris Seymour
This single awkscript is a translation of what you want:
这个单一的awk脚本是你想要的翻译:
awk '{j=0;for(i=4;i<=25;i=3*++j+1)printf "%s %s %s ",$i,$(i+1),$(i+2);print ""}'
You don't need to parse your file 8 times in a shell loop just parse it once with awk.
您不需要在 shell 循环中解析您的文件 8 次,只需使用awk.
回答by Ed Morton
awk -v n="$nprop" 'BEGIN{x=3*n} {a=x; print $++a, $++a, $++a}' file
If you just want your seed value (nprop) to increment on every pass of the file and process the file 8 times, get rid of your external loop and just do this:
如果您只想让您的种子值 (nprop) 在文件的每次传递中递增并处理文件 8 次,请摆脱外部循环并执行以下操作:
awk 'BEGIN{for (i=2;i<=8;i++) ARGV[++ARGC] = ARGV[1]} {a=3*NR/FNR; print $++a, $++a, $++a}' file
In GNU awk you can replace NR/FNR with ARGIND.
在 GNU awk 中,您可以用 ARGIND 替换 NR/FNR。
回答by cdarke
Use a BEGIN{ }block to create a couple of awk variables:
使用一个BEGIN{ }块来创建几个 awk 变量:
avg=$((1+3*$nprop))
awk -v a=$avg 'BEGIN{ap1=a+1;ap2=a+2} {print $a " " $ap1 " " $ap2}' $filename5 >> neig5.dat

![Bash 脚本错误:[: 丢失]](/res/img/loading.gif)