【发布时间】:2014-08-19 00:05:15
【问题描述】:
如果我们有一个像这样的 AWK 脚本 (average.sh) 并且想用它来处理大量的输入文件:
awk -F\" 'BEGIN{print}
last != $4""$8 && last{
print line,exp(C/D)
C=D=0}
{ # This block process each line of infile
C += log($(NF-1)+0)
D++
$(NF-1)=""
line=$0
last=$4""$8}
END{ # This block triggers after the complete file read
# to print the last average that cannot be trigger during
# the previous block
print line,exp(C/D)}' ${var2:=infile}
如果我们这样做了
export var2="infile4" | sh average.sh
“average.sh”仍然处理“infile”而不是“infile4”。
按照Override a variable in a Bash script from the command line 中的最佳答案,我们尝试
var2=infile4 ./geometric_average_real
这会给出“var2=infile: Command not found”的错误。
我们的最终目标是编写循环
for (X=1; X<=3; X++)
do
sh average.sh infile${X}
done
所以这个循环应该处理
sh average.sh infile1
sh average.sh infile2
sh average.sh infile3
【问题讨论】:
-
export var2="infile4" | sh average.sh不应使用管道。那应该是分隔命令的分号。管道正在给您带来问题,因为您正在生成子壳。尝试不使用它。 -
var2=infile4 ./geometric_average_real在bash中应该可以正常工作,但在其他shell 中可能无法正常工作(几乎可以肯定在sh中不行)。如果您想要bash语义,请确保您尝试使用bash而不是sh。 -
如果您在 shell 脚本中使用位置参数参数而不是命名变量(如
var2),则使用类似目标的参数应该可以正常工作。您是否尝试过,但它以某种方式不起作用? -
是的,伊坦! "export var2="infile4" ; sh average.sh" 有效!
-
对了,你不用写
$4""$8。$4 $8可以正常工作,$4$8也可以。如果a和b是两个变量,则a b是它们的字符串连接。只需注意 awk 对于不可见的连接运算符的奇怪表达式优先级。
标签: bash variables awk overwrite