如何将 awk 变量保留在作用域内?

如何将 awk 变量保留在作用域内?

我正在尝试跟踪县和人口列表中的最低/最高值。我不知道如何阻止变量将自身重置为 0。

这是我的 cmd.awk 文件。

BEGIN {
    FS="\t"
    HPD=0
    HPDname=""
    LPD=0
    LPDname=""
    HPW=0
    HPWname=""
    LPW=0
    LPWname=""
}
# Stuff in here needs to be printed during the process.
{
  print $1
  PD=$2/$4
  print PD
  PW=($3/($3+$4))*100
  print PW

# These if statements see if there is a new highest or lowest value for the     categories.
  if ($PD>$HPD)
  {
    HPD=$PD
    HPDname=$1
  }
  if ($PD<$LPD)
  {
    LPD=$PD
    LPDname=$1
  }
  if ($PW>$HPW)
  {
    HPW=$PW
    HPWname=$1
  }
  if ($PW<$LPW)
  {
    LPW=$PW
    LPWname=$1
  }
}

# Prints off all of the ending information that we have been keeping track      of.
END {
    print "The highest population density: "$HPDname" "$HPD
    print "The lowest population density: "$LPDname" "$LPD
    print "The highest percentage of water: "$HPWname" "$HPW
    print "The lowest percentage of water: "$LPWname" "$LPW
}

END 的输出始终显示要分析的最后一个县,而不是跟踪最高或最低。

答案1

为了澄清评论者在代码中指出的内容:

BEGIN {
    FS="\t"
    HPD=0
    HPDname=""
    LPD=0
    LPDname=""
    HPW=0
    HPWname=""
    LPW=0
    LPWname=""
}
# Stuff in here needs to be printed during the process.
{
  print $1
  PD=$2/$4
  print PD
  PW=($3/($3+$4))*100
  print PW

# These if statements see if there is a new highest or lowest value for the     categories.
  if (PD>HPD)
  {
    HPD=PD
    HPDname=$1
  }
  if (PD<LPD)
  {
    LPD=PD
    LPDname=$1
  }
  if (PW>HPW)
  {
    HPW=PW
    HPWname=$1
  }
  if (PW<LPW)
  {
    LPW=PW
    LPWname=$1
  }
}

# Prints off all of the ending information that we have been keeping track      of.
END {
    print "The highest population density: "HPDname" "HPD
    print "The lowest population density: "LPDname" "LPD
    print "The highest percentage of water: "HPWname" "HPW
    print "The lowest percentage of water: "LPWname" "LPW
}

你混淆了 Bash 之类的变量语法和 awk。

重击:

variable='something'
echo $something

awk:

variable="something"
print variable

awk 使用 $ 作为字段变量,例如 $1、$2、$0、$NF,但不适用于您创建的变量。我认为这在技术上或多或少是正确的,尽管我不得不承认我从未阅读过具体细节。

变量赋值

相关内容