使用awk對文檔中特定欄位的排序

來源:互聯網
上載者:User

使用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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.