Gawk print

From wikinotes


Your basic print, like echo.

Multiple items can be printed separated by a comma. They will be output with a space between them by default. $0 prints the entire submitted line

echo "hello" | awk '{$0,"goodbye"}' 
> hello goodbye

$1, $2, $3 etc. prints each entry separated by a token. The default token is a single space.

echo "one two three four" | awk '{print $1 $3}'
> one three


By default, every print statement is converted to a string. printf allows you to control the output type, and the spacing of elements

%s    # string
%f    # floating point
%i    # integer
%E    # scientific notation
%4s   # string (padded to 4 characters)
%.4s  # string (max 4 characters, truncated if necessary)
echo "one two three" | awk '{ printf(   "%10s %5s %-10s %s",    $1,$2,$3,"\n"   ) }'
>          one     two three
printf statements must be encased in parentheses. The first section specifies the format.

--left alignment
%10s means that the first entry ($1 in this case) is a string and will have a 
'column' 10 characters wide from the start of the word.
ex: {one.......}

--right alignment
%-10s means that the entry ($3) will have a column 10 characters wide, but starting at the end of the word.
ex: {.....three}

you could also just as easily print an integer with:

echo "10.459" | awk '{ printf( "%i", $1) }'
> 10


sprintf is syntactically identical to printf except that instead of printing to the standard output, it is designed to be printed to a variable.

echo "8.234" | awk '{var = sprintf("%f", $1); print var}'