Print a comma except on the last line in Awk

Perlnika picture Perlnika · Jan 25, 2013 · Viewed 13.8k times · Source

I have the following script

awk '{printf "%s", $1"-"$2", "}' $a >> positions;

where $a stores the name of the file. I am actually writing multiple column values into one row. However, I would like to print a comma only if I am not on the last line.

Answer

Michael J. Barber picture Michael J. Barber · Jan 25, 2013

Single pass approach:

cat "$a" | # look, I can use this in a pipeline! 
  awk 'NR > 1 { printf(", ") } { printf("%s-%s", $1, $2) }'

Note that I've also simplified the string formatting.