sort piping to awk array - help please

Hi I'm just learning programming and need some help.

I've taken a data file which has a list of numbers eg:
3
5
32
533
13
2

And I've used sort -n and to sort and then piped it to awk to arrange into an array.

#!/bin/sh

sort -n data.txt |

awk '
{
  array[$2]=$1
}
END{
  for(i in array) {
    print array,i
     }
}
'

I've gotten this far but knowing a little C I know that I'm not loading the array correctly as there should be some sort of loop. But I can't find any good tutorials to show me how to do what I want to do.

Any help would be much appreciated!

Hi.

Where does $2 in array[$2]=$1 come from?

As per the input you've shown, there is no "$2".

What are you hoping to achieve? The order in which elements in a for( i in array ) construct are returned is "arbitrary" (thus, most likely messing up your nicely sorted input).

Ah scott, thanks for that, I removed the $2, I think I added it in when I was testing out some examples I found on the net.

I don't quite understand the second bit your wrote thou. I am now getting the data.txt printed out but not in sort order. So I know what your saying but don't quite know what your getting at. I should also have 20 numbers some of them duplicates but I'm only getting about 14. I think the duplicates are being rolled into one.

Thanks for the speedy reply!

Hi.

I was asking what your intended output should be.

If your sole input is

3
5
32
533
13
2

and you want it sorted numerically, then sort -n will do that without awk.

$ sort -n data.txt
2
3
5
13
32
533

so I'm not sure where awk fits into your problem.

edit: I see you edited your post... something about 20 numbers and you're only getting 14...

sort -n file1 | awk '
  { array[NR] = $0 }
  END { for( i in array )
          print array, i
  }
'

sort -n file1 | awk '
  { array[++C] = $0 }
  END { for( i = 1; i <= C; i++ )
          print array, i
  }
'
1 Like

Thanks for that scott, exactly what I needed to get my head around. Once I (you) had it in the array an understood how it worked in awk the rest was easy, so thank you for that!