Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

filter rows

Status
Not open for further replies.

opert

Technical User
May 4, 2011
6

Hello,

I have the following rows:

1 0.054210 4
1 1.215824 5
1 0.790275 32
1 0.739529 23
3 0.429844 12
3 0.000000 94


I would like to filter the rows in that way if the first column is the same than find the minimum value of the second column and in this case print the corresponding 3rd column..

E.g. taking the input above, I should get

1 0.054210 4
3 0.000000 94

Can anyone help me to solve this?

EDIT:

or rather should get

4
94

(but almost the same)
 
Try this:

Code:
awk '
        min[[blue]$1[/blue]] == [red]"[/red][purple][/purple][red]"[/red] || min[[blue]$1[/blue]] > [blue]$2[/blue] { min[[blue]$1[/blue]]=[blue]$2[/blue]; data[[blue]$1[/blue]]=[blue]$3[/blue] }
        [green]END[/green] { [olive]for[/olive] (i [olive]in[/olive] min) [b]print[/b] data[i] }
' inputfile

Note that the output may not be in the same order as the input (because awk does not sort array indices). If that's important you can add another array to track the order of input lines, or even simpler if you are using GNU awk it has built-in sorting functions.

Annihilannic.
 
sorry, but i got this output, which is not good

output:

1 0.054210 4
1 0.790275 32
1 0.739529 23
3 0.429844 12
3 0.000000 94
23
94
 
That's.... odd. What version of awk are you using and on what platform? Any strange characters in your input data (try cat -vet inputfile to check)?

I tested it on HP-UX with the default awk, and I've also tried under Cygwin with gawk.

Code:
$ cat opert
awk '
        min[$1] == "" || min[$1] > $2 { min[$1]=$2; data[$1]=$3 }
        END { for (i in min) print data[i] }
' inputfile
$ cat inputfile
1 0.054210 4
1 1.215824 5
1 0.790275 32
1 0.739529 23
3 0.429844 12
3 0.000000 94
$ sh opert
4
94
$

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top