Print a comma except on the last line in Awk

前端 未结 6 1862
余生分开走
余生分开走 2021-01-02 00:30

I have the following script

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

where $a stores the name of the fi

6条回答
  •  情歌与酒
    2021-01-02 01:23

    Enjoy this one:

    awk '{printf t $1"-"$2} {t=", "}' $a >> positions
    

    Yeh, looks a bit tricky at first sight. So I'll explain, first of all let's change printf onto print for clarity:

    awk '{print t $1"-"$2} {t=", "}' file
    

    and have a look what it does, for example, for file with this simple content:

    1 A
    2 B
    3 C
    4 D
    

    so it will produce the following:

     1-A
     , 2-B
     , 3-C
     , 4-D
    

    The trick is the preceding t variable which is empty at the beginning. The variable will be set {t=...} only on the next step of processing after it was shown {print t ...}. So if we (awk) continue iterating we will got the desired sequence.

提交回复
热议问题