Skip to content
Latchkey

awk split: Break a Field into an Array

awk split(string, array, separator) divides a string into numbered array elements and returns how many it produced.

When a single field itself holds delimited data, like a/b/c in one column, split parses it into an array you can index.

What it does

split(string, array, sep) splits string on sep into array[1], array[2], ... and returns the element count. sep can be a string or regex; if omitted, FS is used. The array is 1-based, matching field numbering.

Common usage

Terminal
# split a path field on "/"
awk '{n = split($1, a, "/"); print a[n]}' paths.txt
# parse key=value out of a single field
awk '{split($2, kv, "="); print kv[1], kv[2]}' pairs.txt
# count segments in a dotted version
awk '{print split($1, parts, ".")}' versions.txt
# split on a regex separator
awk '{split($0, f, /[ ,]+/); print f[1]}' mixed.txt

Signature

FormWhat it does
split(s, a, sep)Split s into array a on sep, return count
split(s, a)Split using FS as the separator
split(s, a, /re/)Split on a regex separator
n = split(...)Capture the number of pieces
a[1], a[n]First and last elements (1-based)

In CI

split parses a compound field, such as image:tag or a slash-delimited ref, without a second awk pass. The return value is the element count, so a[split($1,a,"/")] reaches the last segment in one expression.

Common errors in CI

split arrays are 1-based; reading a[0] yields nothing. The array is not cleared between lines unless you split into it again or delete it, so a shorter line can leave stale elements from a longer prior line; re-split or delete the array first. A single-character separator that is a regex metacharacter (like .) splits on every character unless you pass it as a one-char string, which awk treats literally.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →