Search code examples
shellawkseparator

Print a comma except on the last line in Awk


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.


Solution

  • I would do it by finding the number of lines before running the script, e.g. with coreutils and bash:

    awk -v nlines=$(wc -l < $a) '{printf "%s", $1"-"$2} NR != nlines { printf ", " }' $a >>positions
    

    If your file only has 2 columns, the following coreutils alternative also works. Example data:

    paste <(seq 5) <(seq 5 -1 1) | tee testfile
    

    Output:

    1   5
    2   4
    3   3
    4   2
    5   1
    

    Now replacing tabs with newlines, paste easily assembles the date into the desired format:

     <testfile tr '\t' '\n' | paste -sd-,
    

    Output:

    1-5,2-4,3-3,4-2,5-1