Appending an element to associative array awk -
i've got input file (input.txt) few fields:
a1 b1 c1 d1 e1 a2 b2 c2 d1 e2 a3 b3 c3 d2 e3 a4 b4 c4 d2 e4
and want append elements of associative array,
awk '{a[$4]=a[$4] $5; print a[$4]} end {for(b in a) {print a[b]}}' input.txt
i think output should (ie e2 concatenated e1, , e4 concatenated e3):
e1 e2 e3 e4
but instead output is:
e2 e4
i'm not sure what's wrong code?
your output isn't consistent command, assume want following:
- build list of 5th-column values each unique 4th-column value
- print these lists, preceded respective 4th-column value
a naïve fix want be:
$ awk '{a[$4]=a[$4] " " $5} end {for (b in a) { print b; print a[b]}}' input.txt d1 e1 e2 d2 e3 e4
but there 2 things note:
- the accumulated 5-th column values have leading space - happens grouped output in case.
- due enumerating keys
for (b in a)
, 4th-column values not appear in order appear in input, because order inawk
enumerates keys of [always associative] arrays based on internal hash values, has no guaranteed relationship order in array elements added (nor guarantee particular order in general).
Comments
Post a Comment