Awk BEGIN/END tutorial

In AWK, the BEGIN and END blocks are special code blocks that are executed before and after processing the input, respectively. These blocks are useful for initializing variables, performing cleanup operations, or generating summary reports.

Syntax:

The syntax for BEGIN and END blocks in AWK is as follows:

BEGIN {
# Code to be executed before processing the input
}

END {
# Code to be executed after processing the input
}


Examples:

1. Counting the number of words in a file

BEGIN {
count = 0
}

{
count += NF
}

END {
print "Total words: " count
}
awk 'BEGIN { count = 0 } { count += NF } END { print "Total words: " count}' input.txt

In this example, the BEGIN block initializes the variable count, and then for each line, the number of fields (i.e., words) is added to count. Finally, the END block prints the total number of words.

2. Calculating the average of numbers in a file

BEGIN {
    sum = 0
    count = 0
}

{
    for (i = 1; i <= NF; i++) {
        if ($i ~ /^[0-9]+$/) {
            sum += $i
            count++
        }
    }
}

END {
    print "Average: " sum / count
}
awk 'BEGIN {sum = 0;count = 0;}{ for (i = 1; i <= NF; i++) {if ($i ~ /^[0-9]+$/) {sum += $i;count++;}}} END { print "Average: " sum / count }' input-1.txt

In this example, the BEGIN block initializes the sum and count variables. For each line, it iterates through the fields, checks if they are numbers, and adds them to the sum while incrementing the count. The END block then prints the average value.

3. Reversing all lines in a file

BEGIN {
    RS = "\n"
    FS = ""
    ORS = "\n"
}

{
    for (i = NF; i > 0; i--) {
        printf "%s ", $i
    }
    printf "\n"
}
awk 'BEGIN {RS = "\n";FS = "";ORS = "\n";}{ for (i = NF; i > 0; i--) { printf "%s ", $i; } printf "\n"}' input.txt

In this example, the BEGIN block sets the input record separator (RS), field separator (FS), and output record separator (ORS). For each line, it iterates through the fields in reverse order and prints them, effectively reversing the lines in the file.

In summary, BEGIN and END blocks in AWK are powerful tools for performing operations before and after processing input, and they can be used for a wide range of tasks such as initialization, cleanup, and generating summary reports.

Add a Comment

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