Using sort with awk script

I have a file with four fields and an awk script that strips out one field displaying the remaining three. I have added headings for each of these fields such as Player - Year - RBIs then below it comes the data. What I am trying to do is sort the RBIs field in my script from most to least at the shell prompt using the sort command ...however, the headings are also getting sorted! How can I disclude (heh, not even a word, but sounds right) the three headings from my sort?

Trellot

For example, I have this:

BEGIN { printf("%8s%12s%9s\n", "Player", "Year", "RBIs")
printf("\n") }
{ printf("%8s%12s%10s\n", $1, $2, $4) }

then i type into the shell: awk -f "script" "file" | sort -k 3nr

but then my headings go to the bottom of the output. Can you sort specific lines within their respective field, thus leaving my headings alone?

hmm....

Can't think of a clean solution here. You may wanna try:

head -1 "file" ; awk -f "script" "file" | sed -n '2,$p' | sort -k 3nr

HTH

Will try this, thank you.

Trellot

So I tried your solution and it does sort the file properly, however my heading does not show, rather line 4 (out of 6 lines) repeats itself at the top. What to do? thinking, thinking, thinking....

btw, what does the head -1 do?

Trellot

Any ideas on how to sort my script without also sorting the headings? I just need field four to sort and just the numbers. Here is my script again:

BEGIN { printf("%8s%12s%9s\n", "Player", "Year", "RBIs")
printf("\n") }
{ printf("%8s%12s%10s\n", $1, $2, $4) }

when I sort at the shell...Player, Year and RBIs are sorted into the output.

Thanks all,

Trellot

I've tried using an echo statement before the BEGIN command but that just repeats at the bottom over and over totaling the number of lines I have in the file.

Is there anyway to sort per line number in the script and then the field #?

BEGIN { printf("%8s%12s%9s\n", "Player", "Year", "RBIs")
           printf("\n") }
        { printf("%8s%12s%10s\n", $1, $2, $4) | "sort -k 3nr" }

awk -f "script" file

Thanks Shamrock, I ended up having to edit the source file to add the three headings then run this code that was presented to me earlier to get things to work:

head -2 "file" ; awk -f "script" "file" | sed -n '3,$p' | sort -k 3nr

I was thinking there must be a way to work with the script alone on this issue and your solution worked great. Thank you.

Trellot

@shamrock

Well, we learn new things every day - I didn't know that we could pipe out stuff to external programs - within awk! :slight_smile:

@Trellot

Glad that the solution works for you. Just my 2c - avoid doing formatting before data processing. You are first formatting (using printf) and then processing the formatted data (using sort). Tommorrow if you change your formatting printf, you will be forced to change your sort routine too.