Sorting a tab delimited file
Using bash, this will do the trick:
$ sort -t$'\t' -k3 -nr file.txt
Notice the dollar sign in front of the single-quoted string. You can read about
it in the ANSI-C Quoting sections of the bash man page.
Sort a tab delimited file based on column sort command bash
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?
How do I sort a tab separated file on the nth column using cygwin sort?
On my machine (Mac bash prompt, GNU sort ...) this works:
sort -t ' ' -k 2,2 in.txt > out.txt
(A "real" tab between the quotes.)
To get the tab there I type CTRL-V, TAB (CTRL-V followed by TAB).
EDIT: I've now tested it on a Windows machine from the cygwin prompt and it works the same there (as I expected, bash is bash).
Sorting data based on second column of a file
You can use the key
option of the sort
command, which takes a "field number", so if you wanted the second column:
sort -k2 -n yourfile
-n
,--numeric-sort
compare according to string numerical value
For example:
$ cat ages.txt
Bob 12
Jane 48
Mark 3
Tashi 54
$ sort -k2 -n ages.txt
Mark 3
Bob 12
Jane 48
Tashi 54
Sort rows in a tab delimited file with numerical order
Specify the character index where numbers begin in the field in KEYDEF. In this case we want to sort on the numeric part of the first field, which begins from the 3rd char, thus -k1.3n
:
$ sort -k1.3n file
ch1 1 209
ch1 23 890
ch3 45 21
ch4 66 12
ch10 11 53
ch10 12 90
Related Topics
How to Continue One Thread at a Time When Debugging a Multithreaded Program in Gdb
How to Simulate a Failed Disk During Testing
Use Grep to Find Content in Files and Move Them If They Match
Using Rsync Include and Exclude Options to Include Directory and File by Pattern
Detecting Keyboard, Mouse Activity in Linux
How to Use Variables in a Bash for Loop
Encrypt a String Using Openssl Command Line
One Core Exclusively for My Process
Export Not Working in My Shell Script
Sed Command with -I Option (In-Place Editing) Works Fine on Ubuntu But Not MAC
Remove Line of Text from Multiple Files in Linux
Adding Timestamp to a Filename with Mv in Bash