awk length: Measure Lines and Fields
awk length returns the number of characters in a string, defaulting to the whole line when called bare.
Filtering out short or overlong lines, or measuring a field, is a length one-liner. Bare length and length($0) both measure the current line.
What it does
length(string) returns the character count of its argument; length() or a bare length returns the length of $0. It measures characters, which in a UTF-8 locale may differ from bytes. It is handy as a filter when paired with a comparison.
Common usage
# print lines longer than 80 characters
awk 'length > 80' source.txt
# print each line prefixed by its length
awk '{print length($0), $0}' file.txt
# fields whose value is at least 10 chars
awk 'length($2) >= 10 {print $2}' data.txt
# skip empty lines (length 0)
awk 'length' input.txtForms
| Call | What it does |
|---|---|
| length | Length of $0 (bare, no parentheses) |
| length($0) | Length of the whole line |
| length($2) | Length of field 2 |
| length("text") | Length of a literal string |
| length > 80 | As a pattern: lines longer than 80 chars |
| length(arr) | gawk: number of elements in an array |
In CI
awk 'length > N' flags lines exceeding a length budget (long log lines, oversized config values) in one pass. In gawk, length(array) counts elements, which is a quick way to report how many unique keys you collected; mawk does not support that form.
Common errors in CI
length(array) works in gawk but errors or misbehaves in mawk and some BSD awks, which only accept a scalar; count elements with a loop there. In a multibyte locale, length counts characters while a byte-oriented tool counts bytes, so a length check and a byte budget can disagree. A bare length used where a string was expected returns a number, not the line.