Is there a way to ignore header lines in a UNIX sort?

后端 未结 12 2222
余生分开走
余生分开走 2020-11-28 21:02

I have a fixed-width-field file which I\'m trying to sort using the UNIX (Cygwin, in my case) sort utility.

The problem is there is a two-line header at the top of t

12条回答
  •  清歌不尽
    2020-11-28 21:23

    Here's a bash shell function derived from the other answers. It handles both files and pipes. First argument is the file name or '-' for stdin. Remaining arguments are passed to sort. A couple examples:

    $ hsort myfile.txt
    $ head -n 100 myfile.txt | hsort -
    $ hsort myfile.txt -k 2,2 | head -n 20 | hsort - -r
    

    The shell function:

    hsort ()
    {
       if [ "$1" == "-h" ]; then
           echo "Sort a file or standard input, treating the first line as a header.";
           echo "The first argument is the file or '-' for standard input. Additional";
           echo "arguments to sort follow the first argument, including other files.";
           echo "File syntax : $ hsort file [sort-options] [file...]";
           echo "STDIN syntax: $ hsort - [sort-options] [file...]";
           return 0;
       elif [ -f "$1" ]; then
           local file=$1;
           shift;
           (head -n 1 $file && tail -n +2 $file | sort $*);
       elif [ "$1" == "-" ]; then
           shift;
           (read -r; printf "%s\n" "$REPLY"; sort $*);
       else
           >&2 echo "Error. File not found: $1";
           >&2 echo "Use either 'hsort  [sort-options]' or 'hsort - [sort-options]'";
           return 1 ;
       fi
    }
    

提交回复
热议问题