AWK · Lesson 1 · On the house

Hello, AWK: running gawk, BEGIN and print

Run AWK programs with gawk, learn the pattern-action shape, and print text, numbers and formatted output from a BEGIN block. Lesson 1 is free — on the house.

Lessons · AWK · Lesson 1 of 10 · On the house

Hello, AWK: running gawk, BEGIN and print

Run AWK programs with gawk, learn the pattern-action shape, and print text, numbers and formatted output from a BEGIN block.

Illustration for AWK
Lesson 1 is on the house.

AWK is a text-processing language created at Bell Labs in 1977 by Alfred Aho, Peter Weinberger and Brian Kernighan; the name is their initials. These lessons use GNU Awk (gawk) 5. gawk -f hello.awk data.txt runs a program file over data.txt, and a short program can go on the command line in single quotes: gawk '{ print $1 }' data.txt.

Many systems install a different implementation as plain awk: Debian and Ubuntu often ship mawk, and macOS ships the BSD one-true-awk. The programs in this course stick to POSIX AWK, so they also run there, but always test with the interpreter you deploy on.

An AWK program is a list of rules, each written pattern { action }. AWK reads its input one record (normally one line) at a time and runs every rule whose pattern matches that record. Rules run in the order they appear in the program.

BEGIN is a special pattern that matches once, before any input is read. A program that has only BEGIN rules never reads input at all, so gawk 'BEGIN { print 6 * 7 }' prints 42 and exits.

print writes its arguments followed by a newline. Arguments separated by commas are joined with the output field separator, a single space by default. Writing two values side by side with no comma concatenates them, so print "a" "b" prints ab.

printf format, values... works like C's printf: %s for strings, %d for integers, %f for decimals, %-6s to left-justify in 6 columns and %5.2f for width 5 with 2 decimals. Unlike print, printf adds no newline, so end the format with \n.

A # starts a comment that runs to the end of the line. Statements are separated by newlines or semicolons, and a line ending in a comma, {, && or || continues onto the next line.

hello.awk

# hello.awk : run with  gawk -f hello.awk
BEGIN {
    print "Hello, AWK!"
    print "two", "items"          # a comma prints OFS (a space) between
    print "glued" "together"      # side by side means concatenation
    print 6 * 7
    printf "%s is %d years old\n", "AWK", 2026 - 1977
    printf "%-6s|%5.2f|\n", "pi", 3.14159
}
Match this when you type.

Quiz

What does print "glued" "together" output?

Quiz

When does a BEGIN rule run?

Quiz

What separates the items in print "two", "items"?

Quiz

Which statement prints 3.14 in a 5-wide field followed by a newline?

Check

Match the still for: Hello, AWK: running gawk, BEGIN and print.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.