awk変数を範囲内に保持する方法は?

awk変数を範囲内に保持する方法は?

郡と人口のリストで最も低い/最も高い値を追跡しようとしています。変数がゼロにリセットされるのを停止する方法がわかりません。

これは私の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

奇妙な:

variable="something"
print variable

awkは$ 1、$ 2、$ 0、$ NFなどのフィールド変数に$を使用しますが、ユーザーが作成した変数には使用しません。私はこれが技術的にやや正確だと思いますが、具体的な内容を読んだことがないことを認めなければなりません。

変数の割り当て

おすすめ記事