# Awk

# awk

`pattern {action}`  
`pattern {action}`

`$ awk '{print $2}' /etc/fstab`

to filter out comment lines - starting with #

`$ awk '/^[^#]/ {print $2}' /etc/fstab`

to grep on TWO occurences (AND operator)

`$ awk '/pattern1/ && /pattern2/' /var/log/messages`

case insensitive

`$ awk '/pattern1/ && /pattern2/' IGNORECASE=1 /var/log/messages`

print first field from password file using field seperator ':'

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

print only user ID &gt; 500

`$ awk -F: '$3>=500 {print$1}' /etc/passwd`

display average of numbers entereed on a line:

`$ awk '{ sum=0; for (i=1; i<=NF; i++) sum +=$i; print sum/NF; }'`

<table id="bkmrk-nf-number-of-fields-"><tbody><tr><td>NF

</td><td>number of fields in the current line

</td></tr><tr><td>NR

</td><td>the current record number (line number)

</td></tr><tr><td>FS

</td><td>input field seperator (space by default)

</td></tr><tr><td>RS

</td><td>record seperator (newline by default)

</td></tr><tr><td>Example

</td><td>Example

</td></tr><tr><td>Example

</td><td>Example

</td></tr><tr><td>Example

</td><td>Example

</td></tr><tr><td>Example

</td><td>Example

</td></tr><tr><td>Example

</td><td>Example

</td></tr></tbody></table>

show the 5th record on the second line:

`df  /tmp | awk 'NR==2 {print$5 }'`

## use awk with a program

the file **maxuid**:

```
BEGIN {maxuid = 0; FS=":" }
{ if ($3 > maxuid) maxuid = $3 }
END { print" the largest UID is ", maxuid }
```

then use awk like this:

`$ awk -f maxuid /etc/passwd`

to ignore user nobody:

```
BEGIN {maxuid = 0; FS=":" }
$1 != "nobody" { if ($3 > maxuid) maxuid = $3 }
END { print" the largest UID is ", maxuid }
```

cat -n: (adds line numbers)

`$ awk '{ print NR, $0}' /etc/fstab`

wc -w: (count words)

`$ awk '{ w += NF } END { print w}' /etc/fstab`

grep chris /etc/passwd:

`$ awk '/^chris/' /etc/passwd`

## writing self contained scripts

```
#!/usr/bin/awk -f
{ cost[$1] += $2*$4 }
END { for (cat in cost) print cat, cost[cat] }
```

`chmod u+x catscript`  
`./catscript `

[http://www.pement.org/awk/awk1line.txt](http://www.pement.org/awk/awk1line.txt)