Search code examples
linuxbashshellscriptingsuse

How do I sort a file after a certain row in bash?


I am trying to sort a file and store the output into a tmp file. This is what my file looks like:

this_is_my_file (with no extension)

Names   Last_Name_Initial
---
Alex   G
Nick   D
Jon   J
Cain   V
Anderson   S
Chris   W

I know the command to sort the file is sort -n $PWD/this_is_my_file -o tmp but how to I start the sort after the ---? And a follow up question, how can you distinguish between a text or xml file if the file you are comparing has no extension?


Solution

  • You can use:

    head -n 2 file && tail -n +3 file | sort
    Names   Last_Name_Initial
    ---
    Alex   G
    Anderson   S
    Cain   V
    Chris   W
    Jon   J
    Nick   D
    

    It does the job as follows:

    1. Uses head -n 2 to get first 2 header lines
    2. Used tail -n +3 to get all lines starting from 3rd line
    3. Pipes tail's output with sort
    4. Merges head's output with tail+sort using &&

    To redirect output you can use grouping in shell {...}

    { head -n 2 file && tail -n +3 file | sort; } > output