Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 在命令行/母脚本中重写AWK脚本中的变量_Bash_Variables_Awk_Overwrite - Fatal编程技术网

Bash 在命令行/母脚本中重写AWK脚本中的变量

Bash 在命令行/母脚本中重写AWK脚本中的变量,bash,variables,awk,overwrite,Bash,Variables,Awk,Overwrite,如果我们有这样一个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=$

如果我们有这样一个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”仍然处理“infle”而不是“infle4”

按照中的最佳答案,我们尝试

var2=infile4 ./geometric_average_real
这将导致错误“var2=infle:Command not found”

我们的最终目标是编写循环

for (X=1; X<=3; X++)

do

sh average.sh infile${X}

done

如果average.sh脚本适用于单个内嵌,则只需从另一个脚本调用它,其中包含要处理的文件列表:

#!/bin/bash

test -n "$1" || { echo "error, insufficient input"; exit 1; }

avgscript="/path/to/average.sh"

test -x "$avgscript" || { echo "error: required script `$avgscript` not found or not executable"; exit 1; }

for i in "$@"; do

    avgscript "$i"

done

将该文件另存为say
runavg.sh
,然后只需调用
runavg.sh file1 file2 file2

export var2=“infie4”| sh average.sh
就不应该使用管道。这应该是分隔命令的分号。管道会给您带来问题,因为您正在生成子壳。不要这样做。
var2=infile4./geometric\u average\u real
bash
中应该可以正常工作,但在其他shell中可能无法工作(几乎肯定在
sh
中不能)。如果需要
bash
语义,请确保尝试使用
bash
,而不是
sh
。如果在shell脚本中使用位置参数参数而不是命名变量(如
var2
),则使用类似于目标的参数应该可以正常工作。你有没有试过,但不知怎么的,它不起作用?是的,伊坦!“export var2=“infie4”;sh average.sh”有效!顺便说一下,您不需要编写
$4”“$8
$4$8
可以正常工作,就像
$4$8
一样。如果
a
b
是两个变量,
ab
是它们的字符串连接。请注意awk对于隐形连接运算符的奇怪表达式优先级。嗨,大卫,谢谢你的评论!但是,如果我们没有在…print line,exp(C/D)}'后面加上文件名,就会出现错误消息“awk:cmd.line 14^意外换行或字符串结尾”。我在该死的巴什维尔使用“sh average.sh input.csv”。你能把你的整个awk脚本放在上面的脚本中吗?在
$(你的awk脚本“$i”)
for
循环中,它在
$中写着
avgscript
,用双引号把i括起来,让替换工作起来吗;do
还将循环所有位置参数。
#!/bin/bash

test -n "$1" || { echo "error, insufficient input"; exit 1; }

avgscript="/path/to/average.sh"

test -x "$avgscript" || { echo "error: required script `$avgscript` not found or not executable"; exit 1; }

for i in "$@"; do

    avgscript "$i"

done