2
10 awhdk;
14 hjoeow;
2  kdkld;
4  jkjdksl

How to sort this based on column one (i.e the count) ?

I'd want to get this output :

14 hjoeow;10 awhdk;4 jkjdksl;2 kdkld

I need both the columns to be printed based on sorting the first column.

4

You can use -k to specify where in the input line the sort key starts and ends.

You use the -n option or add n to the sort key specification to trigger a numeric sort as opposed to a lexical sort by default. And -r to reverse the sort.

Here, for a numerical sort, you don't need to limit the sort key to the sort command. If you do:

sort -rn file

It will treat the whole line as a number. The 14 hjoeow; line for instance will be understood as the 14 number.

You could do:

sort -bk 1,1rn file

To sort on the first field only, but that would make no difference.

The command to join lines is paste with the -s option. You can specify the delimiter with -d. \0 is a special value for the delimiter that means join with nothing in between. So, to get your expected output:

sort -rn file | paste -sd '\0' -

POSIX paste require a filename be passed. - is again a special value that means standard input. You can omit it with some paste implementations.

  • @arun if this answer solves your issue please take a minute and click the check mark under the vote count to the left, this will signify to everyone that your issue's been resolved. – terdon Jun 25 '14 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.