Linux AWK length function: Measure String Length
The length
function in awk allows you to determine the length of a string.
In this tutorial, you’ll learn about the length
function, from simple string length calculations to complex data alignments.
Get String Length
First, let’s start with a basic usage of the length
function in awk
.
Consider you have a text file, sample.txt
.
Each line is a record in the context of awk
. Here’s a simple command to get the length of each line:
awk '{ print length($0) }' sample.txt
Assume sample.txt
contains the following lines:
Welcome to Linux World Enjoy the journey
Output:
22 17
Here, awk
processes each line of the file. $0
represents the entire current line.
Get Array Length
To demonstrate the use of the length
function with arrays in awk
, let’s assume we have an array of customer IDs from a dataset.
Here’s a command that simulates array population and retrieves its length:
awk 'BEGIN { customerIDs["001"] = 1; customerIDs["002"] = 1; customerIDs["003"] = 1; print "Array Length: ", length(customerIDs); }'
In this command we:
- Initiate an
awk
script with theBEGIN
keyword. - Create an associative array named
customerIDs
. - Populate the array with three customer IDs.
- Use
length(customerIDs)
to determine the size of the array. - Print the length of the array.
Output:
Array Length: 3
This output indicates that our customerIDs
array contains three elements.
Get Field Length
In awk
, fields in a record (a line of text) are separated by a delimiter, and each field can be accessed with $n
, where n
is the field number.
Assume you have a file services.txt
:
Internet,Unlimited Plan,30Mbps Mobile,Prepaid,100Min Talktime
Each line in the file is a record, and each record has fields separated by commas (,
).
Let’s say we want to find the length of the second field in each record:
awk -F, '{ print length($2) }' services.txt
Output:
14 7
In this command:
-F,
sets the field separator to a comma.length($2)
calculates the length of the second field in each line.print
outputs this length.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.