Formatting reports with printf in AWK

In AWK, you can format reports using the `printf` function, which allows you to control the spacing, alignment, and precision of output. Here are some commonly used techniques for formatting reports with `printf` in AWK:

– **Field width:** You can specify the width of a field using the `%` operator followed by a number. For example, `%10s` specifies a string field with a width of 10 characters. If the actual string is shorter than 10 characters, the field will be padded with spaces to the left. If the actual string is longer than 10 characters, the field will be extended to accommodate the full string.

– **Left and right alignment:** You can specify the alignment of a field using the `-` operator. For example, `%-10s` specifies a left-aligned string field with a width of 10 characters, while `%10s` specifies a right-aligned string field with a width of 10 characters.

– **Precision:** You can specify the precision of a floating-point field using the `.n` operator, where `n` is the number of decimal places to display. For example, `%.2f` specifies a floating-point field with two decimal places.

Here is an example of using `printf` in AWK to format a report:


`
# Generate a report of the average salary by department
BEGIN {
FS = “,”
printf “%-15s %15s\n”, “Department”, “Average Salary”
printf “%-15s %15s\n”, “———“, “————–”
}
{
salary[$4] += $3
count[$4]++
}
END {
for (dept in salary) {
avg = salary[dept] / count[dept]
printf “%-15s %15.2f\n”, dept, avg
}
}


`

In this example, we use the `printf` function to format a report of the average salary by department. We use the `%` operator to specify the width and alignment of each field, and the `.n` operator to specify the precision of the floating-point field. We also use the `\n` escape sequence to print a newline character at the end of each line.

We use the `salary` and `count` arrays to accumulate the total salary and count of employees by department, respectively. We then use a `for` loop to iterate over each department in the `salary` array, calculate the average salary, and print the department name and average salary in a formatted manner.

These are just a few examples of the techniques that you can use in AWK to format reports with `printf`. Remember that `printf` provides a lot of flexibility in formatting output, and you can use it to generate reports in a wide range of formats.