3

I have a file with entries like the following:

female,9,13,6.3152956461
female,12,12,5.4797699786
female,11,11,3.6421699174
female,9,14,4.5933365997
female,8,14,2.4181574607

etc.

I first want to remove all but the first 2 columns, then separate them by a space instead of a comma. Ultimately though my problem is that I need to sort by column 1, then column 2 but I have to keep the pairing in a given row intact.

I believe that I need to use sed to switch the column deliminator and sort to do the sorting but I can't figure out how to keep the row pairings together between the 2 sorts.

2
  • 1
    I'm uncertain about what you mean by "row pairings". Are the lines (rows) in the file paired in a particular way?
    – Kusalananda
    Sep 21, 2017 at 11:25
  • 6
    Please post the output you're expecting Sep 21, 2017 at 11:39

2 Answers 2

9

You mean like this?

$ sort -t, -k1,1 -k2,2n file
female,8,14,2.4181574607
female,9,13,6.3152956461
female,9,14,4.5933365997
female,11,11,3.6421699174
female,12,12,5.4797699786

This will sort ,-delimited data on the first field alphabetically, then on the second field numerically. The sorting will first sort using the first field, and for records that have identical first fields, the second field will be used for sorting.


To remove the last few columns afterwards (or rather, keep columns 1 and 2):

$ sort -t, -k1,1 -k2,2n file | cut -d, -f1,2
female,8
female,9
female,9
female,11
female,12

To remove that comma too:

$ sort -t, -k1,1 -k2,2n file | cut -d, -f1,2 | tr ',' ' '
female 8
female 9
female 9
female 11
female 12

But this is not needed for the sorting, obviously, as you may tell sort what delimiter to use.

2
  • 2
    The right tools for this job
    – Ikaros
    Sep 21, 2017 at 15:07
  • 1
    The original core of Unix is so elegant. Sep 21, 2017 at 18:20
3

Try this:

awk 'BEGIN {FS=","} {print $1, $2}' file | sort -k1,1 -nk2,2

Explanation:

  1. 'BEGIN {FS=","} {print $1, $2}' - set up field separator to , (space by default) and print only first ($1) and second ($2) fields;
  2. file - you file (you can use pipe instead: cat file | awk etc...);
  3. sort -k1,1 -nk2,2 - sort by first field (-k1,1) and the next step - sort by second field numerically (-nk2,2)

Lets complicate your example (actually your first fields are equal). Suppose you have different input file like this:

male,9,13,6.3152956461
female,12,12,5.4797699786
female,11,11,3.6421699174
male,9,14,4.5933365997
male,8,14,2.4181574607

Output will:

male 8
male 9
male 9
female 11
female 12

Is this what you need?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .