AWK

Sample Programs

data.txt

1 30

2 40

3 20

4 50

Pattern - Mathematical expression

Program to print a line when first column is odd

Action will be executed when the pattern in non zero. That is when odd

odd.awk

BEGIN{

print "Start"

}

$1%2 {print $1}

$ awk -f odd.awk data.txt

Start

1 30

3 20

data.txt

1 30

2 40

3 20

4 50

hello world

a1 22

Pattern - Regular expression

Program to print a line when first column matches with a number

Action will be executed when the regular expression for "starting with a number" is matched

match.awk

$1 ~ /^[0-9]/ {print $0}

$ awk -f match.awk data.txt

1 30

2 40

3 20

4 50

Pattern - Relational expression

Program to print a line when first column is either 1 or 2

rel.awk

$1 == 1 {print $0}

$1 == 2 {print $0}

$ awk -f rel.awk data.txt

1 30

2 40

Pattern - logical expression

Program to print a line when first column is either 1 or 2

logic.awk

$1 == 1 || $1 == 2 {print $0}

$ awk -f rel.awk data.txt

1 30

2 40

Pattern - Range

Program to print line 2 to line 5

range.awk

NR == 2, NR == 5 {print $0}

$ awk -f range.awk data.txt

2 40

3 20

4 50

hello world

data.txt

1 30

2 40

3 20

4 50

Control Action - next

line_next.awk

{

next

print $0

}

$ awk -f line_next.awk data.txt

This wont print anything, since when each line is read, seeing the next keyword execution starts from the beginning. This follows for the whole line and nothing printed

Control Action - getline

line_getline.awk

{

getline

print $0

}

$ awk -f line_getline.awk data.txt

2 40

4 50