Kamis, 19 Maret 2009

Contoh Program AWK

Semua ini sangat menyenangkan, namun setiap contoh hanyalah "gigitan" dari "coins.txt". Mengapa tidak diberikan AWK yang lebih menarik?

Tantangan ini memberikan ide yang praktis untuk memasukkan banyak pernyataan AWK pada baris perintah, sehingga mudah untuk memperbaikinya. Perintah dapat ditulis ke dalam file, dan kemudian AWK dapat menjalankan perintah dari file sebagai berikut:

awk -f <awk program file name>

Dengan cara ini maka ada kemampuan untuk menulis suatu program AWK, kemudian apa yang seharusnya menjadi "master" yang dianalisa dari "coint.txt". Berikut ini adalah hasil keluaran program:


Summary Data for Coin Collection:

Gold pieces: nn
Weight of gold pieces: nn.nn
Value of gold pieces: n,nnn.nn

Silver pieces: nn
Weight of silver pieces: nn.nn
Value of silver pieces: n,nnn.nn

Total number of pieces: nn
Value of collection: n,nnn.nn


Berikut program AWK untuk menghasilkan informasi diatas:

# This is an awk program that summarizes a coin collection.
#
/gold/ { num_gold++; wt_gold += $2 } # Get weight of gold.
/silver/ { num_silver++; wt_silver += $2 } # Get weight of silver.
END { val_gold = 485 * wt_gold; # Compute value of gold.
val_silver = 16 * wt_silver; # Compute value of silver.
total = val_gold + val_silver;
print "Summary data for coin collection:"; # Print results.
printf ("\n");
printf (" Gold pieces: %2d\n", num_gold);
printf (" Weight of gold pieces: %5.2f\n", wt_gold);
printf (" Value of gold pieces: %7.2f\n",val_gold);
printf ("\n");
printf (" Silver pieces: %2d\n", num_silver);
printf (" Weight of silver pieces: %5.2f\n", wt_silver);
printf (" Value of silver pieces: %7.2f\n",val_silver);
printf ("\n");
printf (" Total number of pieces: %2d\n", NR);
printf (" Value of collection: %7.2f\n", total); }

* program ini disimpan dalam file bernama "summary.awk", dan dilewatkan sebagai berikut:

awk -f summary.awk coins.txt

Hasilnya adalah:

Summary data for coin collection:

Gold pieces: 9
Weight of gold pieces: 6.10
Value of gold pieces: 2958.50

Silver pieces: 4
Weight of silver pieces: 12.50
Value of silver pieces: 200.00

Total number of pieces: 13
Value of collection: 3158.50

Pustaka:

AWK PROGRAM EXAMPLE

Tidak ada komentar:

Posting Komentar