简体   繁体   English

在文本文件中连接具有特定模式的行

[英]joining lines with a specific pattern in a text file

I'm trying to join rows based on the first value in a row. 我正在尝试连接基于行中第一个值的行。 My file looks like this: 我的文件看起来像这样:

the structure is: ID, KEY, VALUE 结构是:ID,KEY,VALUE

1 1 Joe
1 2 Smith
1 3 30
2 2 Doe
2 1 John
2 3 20

The KEY stands for some kind of attribute of the ID, in this case KEY '1' is first name, '2' is surname and '3' is age. KEY代表ID的某种属性,在这种情况下,KEY'1'是名字,'2'是姓,'3'是年龄。

The output should look like this: 输出应如下所示:

1 Joe Smith 30
2 John Doe 20

I know that this can be done by fairly simple awk script, but I'm having trouble finding it on SO or with Google. 我知道这可以通过相当简单的awk脚本来完成,但是我无法在SO或Google上找到它。

{
    a[$1,$2]=$3
    if ($1>m) {m=$1}
}
END {
    for(i=1;i<=m;i++)
    {
        j=1
        printf i " "
        while (a[i,j] != "")
        {
            printf a[i,j] " "
            j++
        }
    printf "\n"
    }
}

这个awk命令应该工作:

awk '$2==1{fn=$3} $2==2{ln=$3} $2==3{age=$3} NR>1 && NR%3==0 {print $1,fn,ln,age}' file

awk一种方式

awk '{a[$1]=(a[$1])?a[$1]FS$3:$3}END{for(;x<length(a);)print ++x,a[x]}' <(sort -nk12 file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM