AWK printing formatting help please

Hi all,

Below is my testfile:

COST,31-MAR-2011 01:01:04,31-MAR-2011 11:22:12,622
COST,21-MAR-2011 22:00:20,22-MAR-2011 11:07:23,788
FARE,23-MAR-2011 22:00:22,24-MAR-2011 10:10:46,731
FARE,02-MAR-2011 14:01:50,03-MAR-2011 08:30:54,1110

I need to append a number, for example 700, to the end of each record when the fourth field is >700 so I run the command as below which gives me the output that I wanted.

cat testfile.0 | awk -F, '$4 >= 700' | awk '{ print $0","700 }'

COST,21-MAR-2011 22:00:20,22-MAR-2011 11:07:23,788,700
FARE,23-MAR-2011 22:00:22,24-MAR-2011 10:10:46,731,700
FARE,02-MAR-2011 14:01:50,03-MAR-2011 08:30:54,1110,700

All good so far. Just want to know if there is a "better" way of writing this AWK construct?

Next thing is I wanted to add a column heading and get a clean printed output in tabular format sort of so I did as below:

cat /dev/null > testfile.1
echo "FILE_TYPE,START,END,DURATION,THRESHOLD" >> testfile.1
echo "---------,-----,---,--------,---------" >> testfile.1
cat testfile.0 | awk -F, '$4 >= 700' | awk '{ print $0","700 }' >> testfile.1
cat testfile.1 | awk -F, '{ printf "%-20s \t %-20s \t %-20s \t %-20s \t %-20s \n", $1, $2, $3, $4, $5}'

Output is as below:

FILE_TYPE                START                   END                     DURATION                THRESHOLD
---------                -----                   ---                     --------                ---------
COST                     21-MAR-2011 22:00:20    22-MAR-2011 11:07:23    788                     700
FARE                     23-MAR-2011 22:00:22    24-MAR-2011 10:10:46    731                     700
FARE                     02-MAR-2011 14:01:50    03-MAR-2011 08:30:54    1110                    700

Okay, so far so good. The only thing that I want to know now is whether there is an AWK function that will let me print x-number of dashes? Just so in matches the %-20s that am using in the printf?

I know it's a "cosmetic" thingy, I can easily just type in 20 dashes when am doing the echo. Just thought maybe there is an AWK function that will let me do it the "smart" way or any UNIX command that will let me do the same.

Any tips/suggestions will be much appreciated. Thanks in advance.

For question 1:

awk -F, '$4 >= 700 {print $0 FS "700"}' infile

---------- Post updated at 10:21 PM ---------- Previous update was at 10:13 PM ----------

Question 2:

awk -F , 'BEGIN{print "FILE_TYPE\tSTART\t\t\t\tEND\t\t\t\tDURATION\tTHRESHOLD";
                print "---------\t-----\t\t\t\t---\t\t\t\t--------\t---------"}
          $4 >= 700 {gsub(/,/,"\t\t",$0);print $0 "\t\t700"}' infile

Here is my try aswell for the entire operation.

BEGIN {
frmt="%-20s \t %-20s \t %-20s \t %-20s \t %-20s \n"
dash=sprintf (frmt,"FILE_TYPE","START","END","DURATION","THRESHOLD")
print dash
gsub("[A-Z_]","-",dash)
print dash
}
{
if ( $4 >= 700 ) 
printf frmt, $1, $2, $3, $4,"700"
}
1 Like