如何按特定順序對行進行排序,因為它是自己的行塊
我想將以下文本行排序為特定順序。
sort
我正在使用的命令是刪除空格並將所有行捆綁在一起而沒有空格分隔並將它們按字母順序排列。每個塊有 8 行行數據。session:cabSessionID:052FPBP6Q6X2XGERWHBT
cabLoginID:053XCDTF8D4J6PD3BG8P
loginName:jack
userAgent:Mozilla/5.0
sessionStartTime:2018-10-01T01:04:10.899Z
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:42358792
usedJSHeapSize:423564825:
session:cabSessionID:052FPBP6Q6X2XGERWHJE
cabLoginID:053XCDTF8D4J6PD3BG8P
loginName:jack
userAgent:Mozilla/5.0
sessionStartTime:2018-10-01T01:16:41.558Z
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:17775404020使用
JSHeapSize:44844
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:45252608
usedJSHeapSize:24555080
session:cabSessionID:055S75T4QC8JYC4Q0456
cabLoginID:053XCDTF8D4J6PD3BG8P
loginName:frank
userAgent:Mozilla/5.0
sessionStartTime:2018-11.18-23T
我希望最終結果是這樣的:
loginName:jack
cabLoginID:053XCDTF8D4J6PD3BG8P
session:cabSessionID:052FPBP6Q6X2XGERWHBT
userAgent:Mozilla/5.0
sessionStartTime:2018-10-01T01:04:10.899Z
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:42358792 usedJS4HeapSize:42358792
JS4HeapSize:
loginName:jack
cabLoginID:053XCDTF8D4J6PD3BG8P
session:cabSessionID:052FPBP6Q6X2XGERWHJE
userAgent:Mozilla/5.0
sessionStartTime:2018-10-01T01:16:41.558Z
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:177754040320使用
JSHeapSize:4484S
loginName:fred
cabLoginID:053XCDTF8D4J6PD3BG8P
session:cabSessionID:055S75T4QC8JYC4Q0456
userAgent:Mozilla/5.0
sessionStartTime:2018-10-23T19:11:11.871Z
memoryInfo:jsHeapSizeLimit:2217857988
totalJSHeapSize:
45252550808HeapSize:4525255080
由於您想對“排序”進行硬編碼,因此讓 awk 為關聯數組中的每個塊編譯數據,然後按您想要的順序列印該數組:
腳本文件.awk
BEGIN { FS=":" } /./ { values[$1]=$0 } /^$/ { print values["loginName"] print values["cabLoginID"] print values["session"] print values["userAgent"] print values["sessionStartTime"] print values["memoryInfo"] print values["totalJSHeapSize"] print values["usedJSHeapSize"] print "" delete values } END { print values["loginName"] print values["cabLoginID"] print values["session"] print values["userAgent"] print values["sessionStartTime"] print values["memoryInfo"] print values["totalJSHeapSize"] print values["usedJSHeapSize"] }
然後執行:
awk -f scriptfile.awk < input
作為替代方案,如果您不關心塊行的順序,但確實希望它們仍然保持一致的順序,並且您有 GNU awk,
gnuscript.awk
BEGIN { FS=":" PROCINFO["sorted_in"]="@val_str_asc"; } /./ { values[$1]=$0 } /^$/ { asort(values) for (element in values) print values[element] print "" delete values } END { asort(values) for (element in values) print values[element] }
上面的腳本按字母順序列印每個塊的行:
cabLoginID:053XCDTF8D4J6PD3BG8P loginName:jack memoryInfo:jsHeapSizeLimit:2217857988 session:cabSessionID:052FPBP6Q6X2XGERWHBT sessionStartTime:2018-10-01T01:04:10.899Z totalJSHeapSize:42358792 usedJSHeapSize:36482584 userAgent:Mozilla/5.0 ...