Search code examples
linuxbashwindows-mobilemedian

Median using mobile window bash script


i need to create a file txt that contains a list of Median value that change if i have a file like:

  1. 1
  2. 2
  3. 35
  4. 40
  5. 50

i want an output like

  1. 1
  2. 1.5
  3. 2
  4. 18.5
  5. 35

i tried picking up one number at the time from my input file then using sort but i didn't go far.. i hope i made myself clear, thank you!


Solution

  • You could use awk to realize this. For example when you have your data in a file named in.txt:

     awk '{c[NR]=$1; asort(c); if (NR%2) {print c[(NR+1)/2]} else {print (c[(NR/2)]+c[(NR/2)+1]) / 2.0}}' < in.txt
    

    results in the output

    1
    1.5
    2
    18.5
    35