關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • 字串處理工具: Awk

    Posted on March 26th, 2006 Sam Tang 2 comments

    Awk 是一種字串處理工具,不論在指令模式或者撰寫 Shell Script 時也十分有用,以下是 Awk 的使用例子:

    # awk '{ print }' /etc/passwd

    以上指令將 /etc/passwd 作為 awk 的輸入檔案,並會將 /etc/passwd 檔案的內容逐行輸出。但這樣使用 awk 看不出它的作用,以下是另一個例子:

    # awk -F":" '{ print $1 }' /etc/passwd

    以上例子使用 awk 時加入了 -F 選項,並指定每一行用 ":" 作為分隔字串。而 print $1 的意思是印出分隔後的第一組字串。輸出結果是系統所有帳號的使用者名稱。

    如果將 awk 用管線 (pipe) 和其他指令配合的話,作用會更加大,例如用 "ls -l /etc" 的話,會將/etc 的內容及其他檔案/目錄資料印出,但我不想看建立日期及檔案體積等資訊,只要看檔案/目錄及其權限,可以這樣做:

    # ls -l /etc | awk '{print $1 "\t" $9}'

    因為 awk 預設會用 tab 或空白字串作為分隔,所以今次不用 -F 選擇。以上會將 "ls -l /etc" 的輸出作為 awk 的輸入內容,而會印出分隔後第一及第九組字串,兩個字串中間會用 "\t" 分開。


     

    2 responses to “字串處理工具: Awk”

    1. [...] 字串處理工具: Awk (tags: Tech Guide Awk) [...]

    2. [...] 以上的說明是複製自 這個網頁。我參考了這個網頁,給出了自己的命令。只要使用: [...]

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word