[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Suggestion: Keep headings when sorted

From: Assaf Gordon
Subject: Re: Suggestion: Keep headings when sorted
Date: Fri, 24 Jan 2020 12:15:09 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.3.0


On 2020-01-21 2:14 a.m., Mattias Johansson wrote:
I often find that I want to keep one or a few lines untouched by sort, and end 
up using something like this:

$ awk 'NR == 1; NR > 1 { print $0 | "sort" }'

It would be handy if sort had an option for 'number of heading lines' or 

I imagine something like this:

$ sort -H  # keeps first line in place while sorting the rest

Adding "skip-header" support to GNU sort has been requested and
discussed several times in the past (including by me, seven years

The decision was that such functionality can be easily achieved
using existing tools.

For some more details and past discussions, please see:


The simplest method is:

    $ ANY-PROGRAM | ( sed -u 1q ; sort )

This is slightly simpler and shorter than the above "awk" method.
It requires GNU sed for the "-u/--unbuffered" option.

The above sed+sort invocation can be made into a shell function:

      sorth() { sed -u 1q ; sort "$@"; }

And then use "sorth" instead of "sort"
(nothing the main difference is that "sort" can take input files on the
command line, while "sorth" must take the input from STDIN).


Change "1q" to "3q" or other values to keep more than one line of
headers at the top of the input.

The above shell function can be improved into:

   sorth() { num=$1 ; shift ; sed -u ${num}q ; sort "$@"; }

To accept the number of header lines as a (required) first parameter,
e.g. the following will keep the first the values intact and randomize the remaining 7:

   seq 10 | sorth 3 -R


If all else fails, and such a sort-header program is still needed,
I can offer my own attempt at such a perl-wrapper script,
which I wrote before knowing about the "sed/sort" method:

Hope this helps,

reply via email to

[Prev in Thread] Current Thread [Next in Thread]