Coder Perfect

Sorting a file with tab delimiters

Problem

I have the following data in the following format:

foo<tab>1.00<space>1.33<space>2.00<tab>3

Now I attempted to sort the file by reducing the last field. I tried the following commands, but they didn’t work as well as we had hoped.

$ sort -k3nr file.txt  # apparently this sort by space as delimiter

$ sort -t"\t" -k3nr file.txt
  sort: multi-character tab `\\t'

$ sort -t "`/bin/echo '\t'`" -k3,3nr file.txt
  sort: multi-character tab `\\t'

What is the proper procedure?

Here is a sampling of the data.

Asked by neversaint

Solution #1

This will work if you use bash:

$ sort -t$'\t' -k3 -nr file.txt

The dollar symbol in front of the single-quoted string should be noted. The ANSI-C Quoting parts of the bash man page have more information.

Answered by Lars Haugseth

Solution #2

The field delimiter is set to non-blank to blank transition by default, therefore tab should suffice.

However, because the columns are indexed in base 1 and base 0, you’ll generally want to choose base 0.

sort -k4nr file.txt

to numerically sort file.txt by column 4 in reverse order (However, because the data in the question has a total of five fields, the last field would be indexed 5.)

Answered by laalto

Solution #3

After the -t, you must type ctrl-v, followed by the tab character, in a shell. This form of literal tab entering is supported by the majority of shells I’ve used.

However, be aware that copying and pasting from another location does not always retain tabs.

Answered by Brian Carlsen

Solution #4

For some reason, the $ solution did not work for me. However, inserting the tab character into the command accomplished the following: ‘sort -t” -k2″””””””‘

Answered by Lloyd

Solution #5

awk’print print $1″t”$2″t”$3″t”$4″t”$5′ is a good example. The spaces will become tabs as a result of this.

Answered by Michiel Buddingh

Post is based on https://stackoverflow.com/questions/1037365/sorting-a-tab-delimited-file