AWK Built-in Variables: Enhancing Your Scripts

October 7, 2024

AWK Built-in Variables: Enhancing Your Scripts

Welcome back to our AWK course! In this lesson, we will dive into the world of AWK’s built-in variables. These variables are essential tools that can significantly enhance the functionality of your scripts, allowing for more dynamic and flexible text processing.

What are Built-in Variables?

Built-in variables in AWK are predefined variables that hold specific information about the current input being processed. They provide context and can be used to control the flow of your scripts, making them more powerful and efficient.

Key Built-in Variables

Let’s explore some of the most commonly used built-in variables in AWK:

1. NR (Number of Records)

The variable NR keeps track of the total number of input records (lines) that have been processed so far. This is particularly useful when you want to perform actions based on the record number.

awk '{ print NR, $0 }' input.txt

In this example, NR is printed alongside each line from input.txt, effectively numbering the lines.

2. NF (Number of Fields)

The variable NF represents the number of fields in the current record. This is helpful when you need to know how many pieces of data are present in each line.

awk '{ print NF, $0 }' input.txt

Here, NF will output the number of fields for each line in input.txt.

3. FILENAME

The variable FILENAME contains the name of the current input file being processed. This is useful when you are working with multiple files and need to identify which file each record belongs to.

awk '{ print FILENAME, $0 }' file1.txt file2.txt

In this case, the script will print the filename followed by the content of each line from both file1.txt and file2.txt.

4. FS (Field Separator)

The variable FS defines the input field separator. By default, it is a space or tab. You can change it to any character to split fields differently.

awk 'BEGIN { FS =