Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
Wat het doet
awk reads input line by line and splits each line into fields: $1, $2 … ($0 is the whole line). An awk program is a list of pattern { action } pairs: when the pattern matches a line, the action runs.
Useful built-in variables: NR (line number), NF (number of fields, so $NF = last field), FS (field separator, set with -F), OFS (output separator). BEGIN { } runs before the first line, END { } after the last.
On RHEL, awk is GNU awk (gawk).
Zo schrijf je het
awk [OPTIONS] 'PROGRAM' [FILE...]
awk [OPTIONS] -f PROGRAM-FILE [FILE...]Opties 28
Meest gebruikt
Niets past bij dit filter.
Voorbeelden 13
$ als gewone gebruiker# als root (of met sudo)
1Print one column
awk '{print $1}' /var/log/httpd/access_logField 1 = the client IP address. Fields are split by spaces.
2Use another separator
awk -F: '{print $1, $7}' /etc/passwdUser name and shell.
-F:sets the separator.3Filter by a condition
awk -F: '$3 >= 1000 {print $1}' /etc/passwdOnly normal users (UID 1000 and higher).
4Print lines that match a pattern
awk '/sshd/ {print $1, $2, $3, $5}' /var/log/messagesLike grep, but you choose the columns.
5The last field of each line
awk '{print $NF}' file.txtNF= number of fields, so$NF= the last one.6Sum a column
ps aux | awk 'NR>1 {sum += $6} END {printf "%.1f MiB\n", sum/1024}'Total RSS memory of all processes.
NR>1skips the header.7Disk use above 80%
df -P | awk 'NR>1 && $5+0 > 80 {print $6 " is " $5 " full"}'$5+0turns "85%" into the number 85.8Count lines per value (like a pivot)
awk '{count[$9]++} END {for (c in count) print c, count[c]}' /var/log/httpd/access_logNumber of requests per HTTP status code.
9Pass a shell variable into awk
LIMIT=500; awk -v max="$LIMIT" '$2 > max' usage.txt-vis the safe way; do not put shell variables inside the awk quotes.10Change the output separator to make a CSV
awk -F: 'BEGIN {OFS=","} {print $1, $3, $6}' /etc/passwduser,uid,home for every account.
11Print a range of lines
awk 'NR>=10 && NR<=20' /etc/servicesLines 10 to 20.
12Failed SSH logins per IP
The IP is the 4th field from the end in these log lines.
13Remove repeated lines and keep the order
awk '!seen[$0]++' list.txtPrints each line only the first time it appears.
Niets past bij dit filter.
Let op
- Put the program in single quotes, so the shell does not change
$1. - Without
-F, fields are split on runs of spaces and tabs (good for most command output). - awk counts fields from 1;
$0is the whole line.
Tips om te onthouden
- Pattern { action }.
$1first field,$NFlast,NRline number,-F:separator,END {}totals.