Search code examples
linuxbashshellsh

How to use groupby or aggreation in linux


here is the exemple

[A]
XXXX
SSSS
[B]
EEEEE
EEEEE
[A]
ZZZZ
RRRR
[B]
TTTTT
UUUUU
[C]
OOOOO
ZZZZZ

the question is how can we do in linux shell groupby element to have this result ? :

[A]
XXXX
SSSS
ZZZZ
RRRR
[B]
EEEEE
EEEEE
TTTTT
UUUUU
[C]
OOOOO
ZZZZZ

So if can have a function or script or set of commands to do this task that would help me a lot in my project of auto proxy and load balancers. Thank you


Solution

  • Using awk:

    awk '
    /^\[/ {
      group = $0
      next
    }
    {
      elems[group] = elems[group] $0 ORS
    }
    END {
      for (group in elems)
        printf "%s%s%s", group, ORS, elems[group]
    }' file