使用awk對文檔中特定欄位的排序
----------------------------------------------------
1. 問題定義
現在要對如下文檔按特定欄位排序,
lemo@debian:~/Testspace/awk$ cat fileNameSexSalary Lemoman4000 Jokwoman3000 Jobman6000 Pettyman9000
我現在想對其按Salary從高到低進行排序,這時我們就會想到用資料庫進行排序,這樣的話要把這些資料匯入資料庫,如Mysql, sqlite等,但當我們手頭沒有這些資料庫時,其實我們可以用一個叫做awk的程式設計語言來處理,它的優點是非常適合處理結構化資料。
2. 程式碼分析
# @auth lemo.lu# @data 2011.11.16# use to sort the record with specific field# BEGIN BLOCKBEGIN{ print "BEGIN SORT"}############################################### NR - number of records , start from 1# NF - number of fields# $0 - the whole line # $1,$2 - the first column as $1, the second column as $2##############################################NR==1 { # if number of record equals to 1 for (i=1; i<=NF; i++) { if ( $i == fldName ) { fldNr = i } } head = $0 # store field names that is store in first line next # like continue} # 32 - width => the result is padded with black spaces if the value to be printed# is shorter than this number, There , if the length of sorted value is larger that # 32, the result will be wrong{ values[NR] = sprintf("%32s%s", $fldNr, $0) } # END BLOCKEND { n = asort(values) # sorts the content of values and return the number of elments in the array source, the default order is ascending.) print head if( "des" == order) {for (i=n; i>=1; i--) { print substr(values[i],33) # remove the sort values} } else{for (i=1; i<=n; i++) { print substr(values[i],33) # remove the sort values} }}
我們可以把這代程式放在tst.awk檔案中,以gawk命令調用之。
3. 運行結果
下面是一個升序的結果
lemo@debian:~/Testspace/awk$ gawk -v fldName="Salary" -f tst.awk fileBEGIN SORTNameSexSalary Jokwoman3000 Lemoman4000 Jobman6000 Pettyman9000
下面是一個降序的結果
emo@debian:~/Testspace/awk$ gawk -v fldName="Salary" -v order="des" -f tst.awk fileBEGIN SORTNameSexSalary Pettyman9000Jobman6000 Lemoman4000 Jokwoman3000
呵呵,是不是很簡單啊。一般來說,awk會結合sed來用,sed是一個字元流編輯器,可以很好的完成對多個檔案的一系列編輯工作。
4. 參考
http://www.gnu.org/s/gawk/manual/html_node/String-Functions.html#String-Functions