问题
I am trying to write an AWK script to summarize data on a large text file. The order of the resulting data is important so i can't use sort.
I have tried different variations of FNR==NR but haven't had any luck
Input file
Height 3.5
Weight 12.3
Age 23
:
:
Height 4.5
Weight 15.5
Age 31
:
:
Expected Output
Height 3.5 4.5
Weight 12.3 15.5
Age 23 31
回答1:
With awk:
awk '{a[$1]=a[$1] FS $2} END{for(i in a) print i a[i]}' file
Output:
Weight 12.3 15.5 Height 3.5 4.5 : Age 23 31
Derived from: how to merge rows that share unique IDs into a comma separated table
See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
回答2:
Using awk's array you can group the values.
This is a simplified version:.
BEGIN {
summary["Weight"] = "Weight";
...
}
{
summary[$1] = summary [$1] " " $2
}
END {
print summary["Weight"];
...
}
回答3:
This is not awk but might work for you (GNU sed):
sed -E 'H;g;s/((\n\S+)[^\n]*)(.*)\2(.*)/\1\4\3/;h;$!d;x;s/.//' file
Use the hold space to gather up the results for each key and at end-of-file, remove the introduced newline and print the results.
来源:https://stackoverflow.com/questions/56716292/using-awk-to-merge-unique-rows-based-on-column-one