59

awkクラスを使用して、データの 2 列目の平均を見つけようとしています。これは、インストラクターが提供したフレームワークを使用した現在のコードです。

#!/bin/awk

### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.

# This block of code is executed for each line in the file
{
x=sum
read name
        awk 'BEGIN{sum+=$2}'
        # The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
        # NR is a variable equal to the number of rows in the file
        print "Average: " sum/ NR
        # Change this to print the Average instead of just the number of rows
}

次のようなエラーが表示されます。

awk: avg.awk:11:        awk 'BEGIN{sum+=$2}' $name
awk: avg.awk:11:            ^ invalid char ''' in expression

近いと思いますが、ここからどこへ行くべきか本当にわかりません。クラスで見たものはすべてかなり基本的なものなので、コードはそれほど複雑であってはなりません。私にお知らせください。

4

4 に答える 4

18

あなたの特定のエラーは11行目です:

awk 'BEGIN{sum+=$2}'

これはawkが呼び出される行で、そのBEGINブロックが指定されていますが、既に awk スクリプト内にいるため、指定する必要はありませんawksum+=$2また、入力の各行で実行したいので、BEGINブロック内では実行したくありません。したがって、行は単純に次のようになります。

sum+=$2

次の行も必要ありません。

x=sum
read name

sum最初のものはnamedの同義語を作成するだけでx、2番目のものは何をするのかわかりませんが、どちらも必要ありません。

これにより、awk スクリプトが次のようになります。

#!/bin/awk

### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.

# This block of code is executed for each line in the file
{
    sum+=$2
    # The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
    # NR is a variable equal to the number of rows in the file
    print "Average: " sum/ NR
    # Change this to print the Average instead of just the number of rows
}

Jonathan Leffler の回答では、同じ固定コードを表す 1 つのライナーが awk に与えられ、少なくとも 1 行の入力があることを確認します (これによりゼロ除算エラーが停止します)。もしも

于 2013-10-03T03:22:03.857 に答える