Shell Programming Blog Shell Programming Blog

Wednesday, 26 September 2012

Sorting the file leaving the first line and writing in a file

abu sittik | 10:43 |



Now we can see how to sort a file by leaving the first line as it is. For example, we take a file sample.txt which contains the below data.

chrom:index:forward:reverse
chr01:13:1:2
chr13:23432:4:7
chr01:3445:1:6
chr02:2311:3:1
chr01:212:5:2
chr03:12:1:4
chr02:345:12:6
chr01:45:45:0

If we sort the above data by leaving the first line, the output would be

chrom:index:forward:reverse
chr01:13:1:2
chr01:45:45:0
chr01:212:5:2
chr01:3445:1:6
chr02:345:12:6
chr02:2311:3:1
chr03:12:1:4
chr13:23432:4:7

Now we are going to see the command which sorts the content of the file by ignoring the header line (i.e. the first line). This command sorts the first field in ascending order(String) and the second field in the ascending order(numeric)

head -1 sample.txt  

tail -n +2 sample.txt | sort -t : -k1,1 -k2,2n

1) The first command prints the first line of the file on to the screen.
2) The second command will print all the lines except the first line and then sorts the data using the first field (string sort) and then with the second field(numeric sort).

If you want the output to be written in a file, redirect the output using the re-directional operators.

head -1 sample.txt > output.txt

tail -n +2 sample.txt | sort -t : -k1,1 -k2,2n >> output.txt

The symbol > is for writing into a file. This will clear the output.txt if exists and then writes the data. If the file does not exist, it will create the file and then write the output to it.

The symbol >> will append the data to the existing data in the output.txt file.

1 comment:

  1. Vivek Muralidharan20 July 2015 at 12:32

    Great tutorial!!Thanks!

    ReplyDelete

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
3. Please do not spam, spam comments will be deleted immediately upon my review.

Regards,
Mohamed Abubakar Sittik A

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming