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

后端 未结 12 2172
余生分开走
余生分开走 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:33
    cat file_name.txt | sed 1d | sort 
    

    This will do what you want.

    0 讨论(0)
  • 2020-11-28 21:38

    Here is a version that works on piped data:

    (read -r; printf "%s\n" "$REPLY"; sort)
    

    If your header has multiple lines:

    (for i in $(seq $HEADER_ROWS); do read -r; printf "%s\n" "$REPLY"; done; sort)
    

    This solution is from here

    0 讨论(0)
  • 2020-11-28 21:39

    It only takes 2 lines of code...

    head -1 test.txt > a.tmp; 
    tail -n+2 test.txt | sort -n >> a.tmp;
    

    For a numeric data, -n is required. For alpha sort, the -n is not required.

    Example file:
    $ cat test.txt

    header
    8
    5
    100
    1
    -1

    Result:
    $ cat a.tmp

    header
    -1
    1
    5
    8
    100

    0 讨论(0)
  • 2020-11-28 21:40

    This is the same as Ian Sherbin answer but my implementation is :-

    cut -d'|' -f3,4,7 $arg1 | uniq > filetmp.tc
    head -1 filetmp.tc > file.tc;
    tail -n+2 filetmp.tc | sort -t"|" -k2,2 >> file.tc;
    
    0 讨论(0)
  • 2020-11-28 21:41

    You can use tail -n +3 <file> | sort ... (tail will output the file contents from the 3rd line).

    0 讨论(0)
  • 2020-11-28 21:44

    If you don't mind using awk, you can take advantage of awk's built-in pipe abilities

    eg.

    extract_data | awk 'NR<3{print $0;next}{print $0| "sort -r"}' 
    

    This prints the first two lines verbatim and pipes the rest through sort.

    Note that this has the very specific advantage of being able to selectively sort parts of a piped input. all the other methods suggested will only sort plain files which can be read multiple times. This works on anything.

    0 讨论(0)
提交回复
热议问题