如何将awk用于记录字段开始处最后一个值的put?

如何将awk用于记录字段开始处最后一个值的put?,awk,Awk,我试着在开始时得到所有记录,每个记录的最后一个值,但我不知道怎么做 这是我的意见 grey;5 grey;6 grey;3 blue:2 blue;1 blue;0 red;5 red;7 red;2 我该怎么办 请帮助我如果订单不重要,您可以这样做: awk -F\; '{a[$1]=a[$1]"-"$0} END{for(i in a){x=a[i]; match(x, /[^ -]*$/, b); x=b[0]""x; gsub(/-/,"\n", x); print x} }' File

我试着在开始时得到所有记录,每个记录的最后一个值,但我不知道怎么做

这是我的意见

grey;5 grey;6 grey;3 blue:2 blue;1 blue;0 red;5 red;7 red;2 我该怎么办


请帮助我

如果订单不重要,您可以这样做:

awk -F\; '{a[$1]=a[$1]"-"$0} END{for(i in a){x=a[i]; match(x, /[^ -]*$/, b); x=b[0]""x; gsub(/-/,"\n", x); print x} }' File

red;2
red;5
red;7
red;2
grey;3
grey;5
grey;6
grey;3
blue;0
blue;2
blue;1
blue;0

注意:在示例值中,我假设您的意思是
blue;2
而不是
blue:2

我使用GNU awk,因为数据有多个分隔符,但是如果修复文件中的分隔符,则可以使用任何awk和
-F:
,例如:

$ awk -F"[;:]" '       # set the delimiter
$1!=p && NR>1 {        # then the $1 changes (excluding the start)
    for(j=0;j<=i;j++)  # loop thru all stored entries starting and ending with last
        print a[j]     # and output them
    i=0                # reset array index
}
{
    p=$1               # previous key for detecting the change
    a[0]=a[++i]=$0     # store the last record to array 0 and i
}
END {                  # in the end flush the buffer
    for(j=0;j<=i;j++)
        print a[j]
}' file
grey;3
grey;5
grey;6
grey;3
blue;0
blue:2
blue;1
blue;0
red;2
red;5
red;7
red;2
$awk-F“[;:]”设置分隔符
$1!=p&&NR>1{#然后$1发生变化(不包括开始)
对于(j=0;j
awk -F\; '{a[$1]=a[$1]"-"$0} END{for(i in a){x=a[i]; match(x, /[^ -]*$/, b); x=b[0]""x; gsub(/-/,"\n", x); print x} }' File

red;2
red;5
red;7
red;2
grey;3
grey;5
grey;6
grey;3
blue;0
blue;2
blue;1
blue;0
$ awk -F"[;:]" '       # set the delimiter
$1!=p && NR>1 {        # then the $1 changes (excluding the start)
    for(j=0;j<=i;j++)  # loop thru all stored entries starting and ending with last
        print a[j]     # and output them
    i=0                # reset array index
}
{
    p=$1               # previous key for detecting the change
    a[0]=a[++i]=$0     # store the last record to array 0 and i
}
END {                  # in the end flush the buffer
    for(j=0;j<=i;j++)
        print a[j]
}' file
grey;3
grey;5
grey;6
grey;3
blue;0
blue:2
blue;1
blue;0
red;2
red;5
red;7
red;2