AWK: Insert a row after each group of data

和自甴很熟 提交于 2020-01-06 11:03:53

问题


I have a tab delimited csv file. The file is sorted by the column 6, which is the column that contains the key for each group. What I need is to insert a string after each group as a separator.

Input:

car    camaleon    queso    cabra    coche    531    cama    leon    lechuga
dow    click    comedia    clase    tierno    531    falda    camisa    fiel
rederdd    black    cama    reloj    visel    532    pila    resto    cena
viento    lamer    viperest    cash    win    533    pale    babe    atun
taza    terron    cabron    fisgon    dedo    533    one    table    deep
black    cama     leona    lechuga    pies    534    blast    pin    dead 

Desired output:

car    camaleon    queso    cabra    coche    531    cama    leon    lechuga
dow    click    comedia    clase    tierno    531    falda    camisa    fiel
<string>
rederdd    black    cama    reloj    visel    532    pila    resto    cena
<string>
viento    lamer    viperest    cash    win    533    pale    babe    atun
taza    terron    cabron    fisgon    dedo    533    one    table    deep
<string>
black    cama     leona    lechuga    pies    534    blast    pin    dead 

How I can control when the value of column 6 changes, to insert the string when it happens ?. With AWK.


回答1:


I would use awk. Like this:

awk -F'\t' 'NR>1&&g!=$6{print "----"}{g=$6}1' input.txt

NR>1 checks whether the current record is not the first record. g!=$6 checks whether a variable called g for group is the same as the one saved before. If these both conditions are true the separator is printed.

g=$6 stores the group id in the variable g. 1 is always true and makes awk print the line.



来源:https://stackoverflow.com/questions/33874258/awk-insert-a-row-after-each-group-of-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!