AWK:删除逗号分隔场的第一个和最后条目 [英] awk: delete first and last entry of comma-separated field

查看:169
本文介绍了AWK:删除逗号分隔场的第一个和最后条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面这样的4列数据:

I have a 4 column data that looks something like the following:

 a    1    g    1,2,3,4,5,6,7
 b    2    g    3,5,3,2,6,4,3,2
 c    3    g    5,2,6,3,4
 d    4    g    1,5,3,6,4,7

我想这样的输出看起来象下面先删除两个数字和整个第四列的最后两个数字

I am trying to delete first two numbers and the last two numbers on entire fourth column so the output looks like the following

 a    1    g    3,4,5
 b    2    g    3,2,6,4
 c    3    g    6
 d    4    g    3,6

有人可以给我一个帮助?我想AP preciate它。

Can someone give me a help? I would appreciate it.

推荐答案

您可以使用此:

$ awk '{n=split($4, a, ","); for (i=3; i<=n-2; i++) t=t""a[i](i==n-2?"":","); print $1, $2, $3, t; t=""}' file
a 1 g 3,4,5
b 2 g 3,2,6,4
c 3 g 6
d 4 g 3,6

说明


  • N =拆分($ 4,)切片第四场件的基础上,逗号作为分隔符。由于拆分()返回我们得到的件数,我们把它存储在 N 来与它以后的工作。

  • 为(i = 3; I&LT; = N-2;我+ +)T =一[I](?我== N-2:)商店 T 最后一个字段,通过所有的切片循环。

  • 打印$ 1,$ 2,$ 3吨; T =打印新的输出,并清空变量 T

  • Explanation

    • n=split($4, a, ",") slices the 4th field in pieces, based on comma as delimiter. As split() returns the number of pieces we got, we store it in n to work with it later on.
    • for (i=3; i<=n-2; i++) t=t""a[i](i==n-2?"":",") stores in t the last field, looping through all the slices.
    • print $1, $2, $3, t; t="" prints the new output and blanks the variable t.
    • 这篇关于AWK:删除逗号分隔场的第一个和最后条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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