cancel
Showing results for 
Search instead for 
Did you mean: 

sorting

SOLVED
Go to solution
Leslie Chaim
Regular Advisor

sorting

Hi,

I am trying to sort the output of a given command. However, I wish to exclude the first 3 lines from the sort.

Is there an elegant way of doing this without going through the hassle of temporary files?

currently I use something like this:

my_app $* > /tmp/my_app.$$
head -2 /tmp/my_app.$$
sed -n '3,$p' /tmp/my_app.$$ | sort
rm /tmp/my_app.$$

I am wondering if there is something more elegant

Thanks,

If life serves you lemons, make lemonade
5 REPLIES
James R. Ferguson
Acclaimed Contributor

Re: sorting

Leslie:

Try:

# my_app | awk 'NR > 3 {print $0}' | sort

...JRF...
Leslie Chaim
Regular Advisor

Re: sorting

JRF,

I want to include in the output the top 3 lines. Your solution exlucdes the top lines from the output,
If life serves you lemons, make lemonade
Madhu Sudhan_1
Respected Contributor

Re: sorting

Try this way
# my_app | awk 'NR <= 3 {print $0}' >only_one_file

## my_app | awk 'NR > 3 {print $0}' | sort -o only_one_file

This way you have only one file created at any time.

Regards,
Madhu
Think Positive
James R. Ferguson
Acclaimed Contributor
Solution

Re: sorting

Leslie:

OK, I assume you want to take the output of your process and sort it, but you do not want to include the first three lines of output in the sort -- as in the case of a table with a header. Therefore, consider this example:

Given a file that looks like:

1a
2b
3c
4c
5e
6f
7g

# cat my_file|awk '{if (NR <=3) {print $0} else {print $0|"sort -r"}}'

would produce output ordered:

1a
2b
3c
7g
6f
5e
4d

No temporary files would be used; the first three lines would pass "unsorted", and in this example (clearly) the remaining lines would be sorted (here in reverse).

...JRF...
Leslie Chaim
Regular Advisor

Re: sorting

JRF,

That does solve my problem. I am just wondering how does awk pass the data to the sort command?
If life serves you lemons, make lemonade