# AWK內置變量

AWK提供了幾個內置變量。他們發揮着重要的作用，同時編寫AWK腳本。本章說明了內置變量的使用。

## 標準AWK變量

### ARGC

[jerry]\$ awk 'BEGIN {print "Arguments =", ARGC}' One Two Three Four

Arguments = 5

### ARGV

[jerry]\$ awk 'BEGIN { for (i = 0; i < ARGC - 1; ++i) { printf "ARGV[%d] = %s\n", i, ARGV[i] } }' one two three four

ARGV[0] = awk
ARGV[1] = one
ARGV[2] = two
ARGV[3] = three

### CONVFMT

[jerry]\$ awk 'BEGIN { print "Conversion Format =", CONVFMT }'

Conversion Format = %.6g

### ENVIRON

[jerry]\$ awk 'BEGIN { print ENVIRON["USER"] }'

jerry

### FILENAME

[jerry]\$ awk 'END {print FILENAME}' marks.txt

marks.txt

### FS

[jerry]\$ awk 'BEGIN {print "FS = " FS}' | cat -vte

FS = \$

### NF

[jerry]\$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NF > 2'

One Two Three
One Two Three Four

### NR

[jerry]\$ echo -e "One Two\nOne Two Three\nOne Two Three Four" | awk 'NR < 3'

One Two
One Two Three

### OFMT

[jerry]\$ awk 'BEGIN {print "OFMT = " OFMT}'

OFMT = %.6g

### OFS

[jerry]\$ awk 'BEGIN {print "OFS = " OFS}' | cat -vte

OFS = \$

### ORS

[jerry]\$ awk 'BEGIN {print "ORS = " ORS}' | cat -vte

ORS = \$
\$

### RLENGTH

[jerry]\$ awk 'BEGIN { if (match("One Two Three", "re")) { print RLENGTH } }'

2

### RS

[jerry]\$ awk 'BEGIN {print "RS = " RS}' | cat -vte

RS = \$
\$

### RSTART

[jerry]\$ awk 'BEGIN { if (match("One Two Three", "Thre")) { print RSTART } }'

9

### SUBSEP

[jerry]\$ awk 'BEGIN { print "SUBSEP = " SUBSEP }' | cat -vte

SUBSEP = ^\\$

### \$0

[jerry]\$ awk '{print \$0}' marks.txt

1)    Amit     Physics    80
2)    Rahul    Maths      90
3)    Shyam    Biology    87
4)    Kedar    English    85
5)    Hari     History    89

### \$n

[jerry]\$ awk '{print \$3 "\t" \$4}' marks.txt

Physics    80
Maths      90
Biology    87
English    85
History    89

## GNU AWK specific variables

### ARGIND

[jerry]\$ awk '{ print "ARGIND = ", ARGIND; print "Filename = ", ARGV[ARGIND] }' junk1 junk2 junk3

ARGIND = 1
Filename = junk1
ARGIND = 2
Filename = junk2
ARGIND = 3
Filename = junk3

### ERRNO

[jerry]\$ awk 'BEGIN { ret = getline < "junk.txt"; if (ret == -1) print "Error:", ERRNO }'

Error: No such file or directory

### IGNORECASE

[jerry]\$ awk 'BEGIN{IGNORECASE=1} /amit/' marks.txt

1)    Amit     Physics    80

### LINT

[jerry]\$ awk 'BEGIN {LINT=1; a}'

awk: cmd. line:1: warning: reference to uninitialized variable `a'
awk: cmd. line:1: warning: statement has no effect

### PROCINFO

[jerry]\$ awk 'BEGIN { print PROCINFO["pid"] }'

4316

### TEXTDOMAIN

[jerry]\$ awk 'BEGIN { print TEXTDOMAIN }'

messages