Sie sind auf Seite 1von 9

AWK

A Pattern scanning and processing language


made by
Aho Weinberger Kernighan
and explained by
Albert Montijn
AWK

Usage:
– awk-instructions on the command line

awk 'awk­instructions' filename ...
– awk-instructions in a script file:

awk ­f awk­scriptfile ...
– awk-option: set field-separator

awk ­F: ...
– awk-option: set variable

awk ­v var=value ...
AWK

Statements in an AWK program are built of
lines with patterns and actions:
pattern { action }
pattern { action ; action ; ...}
pattern (missing action)
{ action(s) } (missing pattern)

Patterns:
/regular expression/
$1 == “abc” && NF > 3 || $3 ~ /regex/
BEGIN
END
AWK

Variables:

NR recordnumber

NF number of fields

FS field separator

$n contents of field n. n can be an
expression. Eg.: ${NF­1}

a,b untyped, number or string
reference implies existence

Functies:

length(X), index(s,t)

substr(s,i,n)

sub(r,s,t), gsub(r,s,t)

match(s,r), split(s,a,r)

print, (s)printf(fmt,expr­list)
AWK
Geef antwoord op vragen over /etc/passwd
1.Wat is het aantal regels?
2.Wat is de tiende regel?
3.Wat is het laatste veld van elke regel?
4.Wat is het eerste veld van de laatste regel?
5.Geef alle regels waarvan het derde veld > 20
6.Geef alle regels met een regelnummer
7.Geef alle regels zonder het tweede veld
8.Verwissel alle eerste en laatste velden
9.Geef alle regels met eerste veld korter dan 5
10.Welke regels bevatten /etc in voorlaatste veld?
11.Wat is het totaal aantal velden in de file?
12.Wat is het hoogste waarde van het derde veld?
AWK

Operators in Increasing Precedence

Assignment: = , +=, ­=, *=, /=, %=, ^=

Logical: ||, &&, ~, !~

Relational: <, <=, ==, !=, >=, >

Concatenation: blank

Add/Subtract: +, ­

Multiply/divide/mod: *, /, %

Unary plus, minus, not, exponent (^ or **)

Increment, decrement

Field: $expr
AWK

Arrays

Associative arrays (hash): index can be any 
value (integer or string)

Referencing creates entry:
if (arr[“x”] != “”) print “arr[x] exists”

Control flow statements

if ( expr ) statement [ else statement ]

if ( subscript in array ) ...

while ( expr ) statement

for ( init_expr; test_expr; increment_expr ) statement

for ( subscript in array ) statement

do statement while ( expr )

break, continue, next,
exit [expr], return [expr] 
AWK

Reguliere expressies (in AWK)

c matches non metacharacter c

\c matches literal character c

. matches any character but newline

^ matches beginning of line or string

$ matches end of line or string

[abc...] character class matches any of abc... 

[^...] negated class matches any but ...

r1|r2 matches r1 or r2

r1r2 concatenation: matches r1, then r2

r+matches one or more r's

r*matches zero or more r's

(r) grouping: mathes r
AWK

Functions
– Definition
 func[tion] funcname(parameters...,

local_variables){
...
[return expr]
}

– Usage
[var = ] funcname(actual params)

Das könnte Ihnen auch gefallen