🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Awk Functions

An awk function is a named block of code that takes values and returns one result. It lets one calculation be reused on many lines.

A user-defined function

The double function returns twice its input. Each input line prints its number and its doubled value.

printf '3\n7\n' > nums.txt
awk 'function double(x) {return x * 2} {print $1, double($1)}' nums.txt

split and substr

Split cuts the name at each hyphen, and the pieces are numbered from 1. Substr takes the first three characters of the whole name.

printf 'ada-lovelace\n' > name.txt
awk '{split($1, p, "-"); print p[2]; print substr($1, 1, 3)}' name.txt

toupper and length

Toupper changes each name to upper case. Length counts the characters in each name.

printf 'ada\nben\n' > names.txt
awk '{print toupper($1), length($1)}' names.txt

Example

printf 'ada lovelace\ngrace hopper\n' > people.txt
awk 'function cap(s) {return toupper(substr(s, 1, 1)) substr(s, 2)} {split($0, p, " "); print cap(p[2]) ", " cap(p[1]) " (" length(p[1]) ")"}' people.txt

Key points

  • function: the keyword that starts a user-defined awk function.
  • return: the keyword that sends a result back to the caller.
  • split: a function that cuts a string into numbered pieces.
  • substr: a function that takes part of a string from a position.
  • length: a function that counts the characters in a string.
  • toupper: a function that changes a string to upper case.

In this example, the cap function upper-cases the first letter of a word and keeps the rest unchanged. Each line is split on a space into first and last names. The print step shows the last name first, then the first name, then the length of the first name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does split($1, p, "-") do?