2017-03-22 80 views
-1

林triying讓所有記錄中的認沽在開始每記錄的最後一個值,但我不知道如何怎麼用awk把記錄字段放在最後一個值?

這是我輸入

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

這是我的期望輸出

 
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\; '{a[$1]=$0} $0; END{for(i in a) print a[i]}' file 

what c我烏爾德做

請幫我

回答

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

+1

非常感謝你工作正常;我非常感謝 – victorhernandezzero

1

我使用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 
+0

非常感謝你。 – victorhernandezzero

相關問題