2

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?

Redson
  • 2,098
  • 4
  • 25
  • 50

2 Answers2

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You could use a grouping construct:

{
    # read and print the first 2 lines
    read line; echo "$line"
    read line; echo "$line"
    # and sort the rest
    sort
} < this_is_my_file

Also, awk:

awk 'NR <= 2 {print; next} {print | "sort"}' this_is_my_file

a follow up answer: in general, on a unix-y system, the name file makes no guarantees about the contents of a file. However, you could see what the file command says about a file:

$ cat > contains_xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<foo>
<bar>baz</bar>
</foo>
$ file contains_xml
contains_xml: XML document text
$ cat > not_really.xml
this is plain text
$ file not_really.xml
not_really.xml: ASCII text
glenn jackman
  • 238,783
  • 38
  • 220
  • 352