next up previous contents
Next: awk變數與shell變數 Up: 變數與欄位處理 Previous: 變數與欄位處理   Contents

內定變數

除了像C語法的自訂變數,x,y,z....。awk有一些內定的變數名。 欄位上的內定變數
    ARGC        :  number of arguments on command line
    ARGV        :  array containing the command line arguments
    ARGIND      :  
    $0          :  整行record
    $1....$n    :  第n個欄位(field)
    
    ENVIRON     :  一個associate array含有全部的環境變數
    ERRNO       :  最後system出錯的error number請看/usr/include/errno.h
    
    FILENAME    :  current filename
    FIELDWIDTHS :  list of field widths
   
    FS          :  field separator內定是空白或tab
    OFS         :  output field seperator內定是空白
    RS          :  record separator內定是newline
    ORS         :  output record seperator內定是newline
    NF          :  number of field
    NR          :  number of record
其中FS, OFS, RS, ORS, NF, NR是常用到的請看例子
    $ cat /etc/passwd
    list:x:38:38:SmartList:/var/list:/bin/sh
    irc:x:39:39:ircd:/var:/bin/sh
    nobody:x:65534:65534:nobody:/home:/bin/sh
    cyril:x:1000:1000:Cyril Huang,,,:/home/cyril:/bin/bash

    $ awk '{FS=":"; print $7}' /etc/passwd
    /bin/sh
    /bin/sh
    /bin/sh
    /bin/bash

    $ awk '{FS=":"; OFS=","; print $1,$6,$7}' /etc/passwd
    list,/var/list,/bin/sh
    irc,/var,/bin/sh
    nobody,/home,/bin/sh
    cyril,/home/cyril,/bin/bash

    NF NR可以拿來作condition用
    $1 $2....也可以拿來作condition用,搭配變數regular express match算符 ~

    $ cat datafile
    # This is the data file from experiment
    99      98 3.5
    300     298 4.9
    498     493 5.9
    # Failed data
    122     123
    699     698 7.6
    900     748 9.0
    1200    703 9.6
    1500    651 10.4
    1698    627 10.8

    $ awk 'NF == 3 && $1 ~ /[0-9]+/{print $3,$1,$2}' datafile
    3.5 99 98
    4.9 300 298
    5.9 498 493
    7.6 699 698
    9.0 900 748
    9.6 1200 703
    10.4 1500 651
    10.8 1698 627



Cyril Huang 2002-06-14