In AWK, you can generate reports by processing input data and producing formatted output using a combination of built-in variables, functions, and control structures. Here are some commonly used techniques for generating reports in AWK: - **Control structures:** You can use control structures (`if`, `else`, `while`, etc.) to implement conditional logic and looping in your report generation code. Here is an example of using an `if` statement in AWK to generate a report:
# Generate a report of all employees who earn more than $50,000 per year BEGIN { FS = "," printf "%-20s %-20s %-10s\n", "First Name", "Last Name", "Salary" printf "%-20s %-20s %-10s\n", "----------", "---------", "------" } { if ($3 > 50000) { printf "%-20s %-20s $%-9s\n", $1, $2, $3 } }
“
In this example, we use the `if` statement to check if the salary (`$3`) of an employee is greater than $50,000. If so, we use the `printf` statement to print the employee’s first name (`$1`), last name (`$2`), and salary (`$3`) in a formatted manner.
– **Built-in variables:** AWK providesseveral built-in variables that you can use to generate reports. Here are some commonly used built-in variables:
– `NR`: The current record number (line number) of the input file.
– `FNR`: The current record number (line number) of the current file.
– `FILENAME`: The name of the current input file.
Here is an example of using built-in variables in AWK to generate a report:
# Generate a report of the total number of lines in each input file
BEGIN {
printf “%-20s %s\n”, “File Name”, “Line Count”
printf “%-20s %s\n”, “———“, “———-”
}
{
count[FILENAME]++
}
END {
for (file in ARGV) {
if (file != ARGV[0]) {
printf “%-20s %d\n”, ARGV[file], count[ARGV[file]]
}
}
}
`` In this example, we use the `count` array to store the number of lines in each input file. We then use a `for` loop to iterate over each input file (`ARGV` array) and print the file name (`ARGV[file]`) and line count (`count[ARGV[file]]`) in a formatted manner. - **Functions:** You can use built-in or user-defined functions to implement custom report generation logic. Here isan example of using a built-in function in AWK to generate a report:
# Generate a report of the total number of words in a file { words += NF } END { printf "Total number of words: %d\n", words }
“
In this example, we use the `NF` built-in variable to count the number of words in each line of the input file. We then use the `+=` operator to accumulate the word count in the `words` variable. Finally, we use the `printf` statement to print the total number of words in the file.
These are just a few examples of the techniques that you can use in AWK to generate reports. You can combine these techniques with other AWK features to implement complex reporting and analysis tasks. Remember that AWK is a powerful tool for text processing and manipulation, and can be used to generate reports from a wide range of input data sources.