Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a tab delimited file based on column sort command bash [duplicate]

I am trying to sort this file based on the fourth column. I want the file to reordered based on the values of the fourth column.

File:

2   1:103496792:A   0   103496792
3   1:103544434:A   0   103544434
4   1:103548497:A   0   103548497
1   1:10363487:T    0   10363487

I want it sorted like this:

1   1:10363487:T    0   10363487
2   1:103496792:A   0   103496792
3   1:103544434:A   0   103544434
4   1:103548497:A   0   103548497

I tried this command:

sort -t$'\t' -k1,1 -k2,2 -k3,3 -k 4,4 <filename>

But I get illegal variable name error. Can somebody help me with this?

like image 629
Vignesh Avatar asked Jul 02 '13 16:07

Vignesh


People also ask

How do I sort a specific column in bash?

Sort allows us to sort a file by columns by using the -k option.

How do I sort with delimiter?

To sort by a delimiter pass the -t option to sort along with the delimiter value. For a CSV file this would be , . This can be combined with the -k option to sort on fields within a CSV. The result will be written to standard output.

How do I sort a file in bash?

Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.

How do you sort a column by file in Unix?

5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.


2 Answers

To sort on the fourth column use just the -k 4,4 selector.

sort -t $'\t' -k 4,4 <filename>

You might also want -V which sorts numbers more naturally. For example, yielding 1 2 10 rather than 1 10 2 (lexicographic order).

sort -t $'\t' -k 4,4 -V <filename>

If you're getting errors about the $'\t' then make sure your shell is bash. Perhaps you're missing #!/bin/bash at the top of your script?

like image 199
John Kugelman Avatar answered Sep 22 '22 10:09

John Kugelman


I believe you have an errant $ in your command.

Try:

sort -t\t -nk4
like image 21
Phylogenesis Avatar answered Sep 19 '22 10:09

Phylogenesis