[awk 練習] 使用 getline 來讀取資料

【使用 getline 來讀取資料】
$ vim reformat4.awk
awk ‘
BEGIN {
result = “today_rpt4”
sys_sort = “sort -n >> ” result
“date” | getline
print “Today is: “, $2, $3 > result
print “====================” > result
print “ID Number    Arrival Time” > result
close(result)

FS = “[ t:]”
late_file = $2 “_late.dat”
while (getline < late_file > 0) cnt[$1] = $2
close(late_file)
}

{
arrival = HM_to_M($2, $3)
total += arrival
if (arrival > 480) {
mark = “–”
cnt[$1]++
} else mark = “”

message = cnt[$1] ? cnt[$1] ” times” : “”
printf(“%8s     %2d:%2d %5s %sn”, $1, $2, $3, mark, message) | sys_sort
}

END {
close(result)
close(sys_sort)
printf(“Average arrival time = %d:%dn”, total/NR/60, (total/NR)%60) >> result

for ( any in cnt )
print any, cnt[any] > late_file
}

function HM_to_M(hour, min) {
return hour * 60 + min
}

‘ $*
-> vim 命令模輸入 “:wq” (存檔離開)

(閱讀全文…)

[awk 練習] 改變 AWK 切割欄位的方式 & 使用者定義函數

【改變 AWK 切割欄位的方式 & 使用者定義函數】
$ vim reformat3.awk
BEGIN {
{ “date” | getline
print “Today is: “, $2, $3 > “today_rpt3”
print “====================” > “today_rpt3”
print “ID Number    Arrival Time” > “today_rpt3”
close(“today_rpt3″)
}
{ FS=”[ t:]+”
sys_call = “sort -n >> today_rpt3”
}
}

{    arrival = HM_to_M($2, $3)
total += arrival
printf(“%6s      %2s:%2s %sn”, $1, $2, $3, arrival > 480 ? “–” : “”) | sys_call
}

END {
close(“today_rpt3”)
close(sys_call)
printf(“Average arrival time = %d:%dn”, total/NR/60, (total/NR)%60) >> “today_rpt3”
}

function HM_to_M(hour, min) {
return hour * 60 + min
}
-> vim 命令模輸入 “:wq” (存檔離開)

(閱讀全文…)

[awk 練習] AWK 中如何利用系統資源

【AWK 中如何利用系統資源】
$ vim reformat2.awk
BEGIN {
“date” | getline
printf(“Today is %s %d 日n”, $2, $3) > “today_rpt2”
print “=========================” > “today_rpt2”
print “ID Number   Arrival Time” > “today_rpt2”
close(“today_rpt2”)
}
{ printf(“%6s %10sn”, $1, $2) | “sort -n >> today_rpt2” }
-> vim 命令模輸入 “:wq” (存檔離開)

(閱讀全文…)

[awk 練習] 列印檔案中指定的欄位資料並加以計算

【列印檔案中指定的欄位資料並加以計算】
$ vim emp.txt
A125 Jenny 100 210
A341 Dan 110 215
P158 Max 130 209
P148 John 125 220
A123 Linda 95 210
-> vim 命令模輸入 “:wq” (存檔離開)

$ vim pay1.awk
{ print $2, $3 * $4 }
-> vim 命令模輸入 “:wq” (存檔離開)

$ awk -f pay1.awk emp.txt
Jenny 21000
Dan 23650
Max 27170
John 27500
Linda 19950

$ vim pay2.awk{ printf(“%6s Work hours: %3d Pay: %5dn”, $2, $3, $3 * $4) }
-> vim 命令模輸入 “:wq” (存檔離開)

$ awk -f pay2.awk emp.txt
Jenny Work hours: 100 Pay: 21000
Dan Work hours: 110 Pay: 23650
Max Work hours: 130 Pay: 27170
John Work hours: 125 Pay: 27500
Linda Work hours:  95 Pay: 19950

【資料參考來源】