AWK:在每组数据之后插入一行 [英] AWK: Insert a row after each group of data

查看:230
本文介绍了AWK:在每组数据之后插入一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个制表符分隔的csv文件.该文件按列6排序,该列是包含每个组的键的列.我需要在每个组后面插入一个字符串作为分隔符.

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.

输入:

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 

所需的输出:

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 

如何控制第6列的值何时更改,以在发生字符串时插入字符串?使用AWK.

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

推荐答案

我会使用awk.像这样:

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

NR>1检查当前记录是否不是第一条记录. g!=$6检查用于 group 的名为g的变量是否与之前保存的变量相同.如果这两个条件都成立,则将打印分隔符.

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将组ID存储在变量g中. 1始终为true,并使awk打印行.

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

这篇关于AWK:在每组数据之后插入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆