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?
Sort allows us to sort a file by columns by using the -k option.
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.
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.
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.
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?
I believe you have an errant $
in your command.
Try:
sort -t\t -nk4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With