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:

  1. Initiate an awk script with the BEGIN keyword.
  2. Create an associative array named customerIDs.
  3. Populate the array with three customer IDs.
  4. Use length(customerIDs) to determine the size of the array.
  5. 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.
Leave a Reply

Your email address will not be published. Required fields are marked *