简体   繁体   中英

Using AWK find a smallest number in a second column bigger than x

I have a file with two columns,

sdfsd 1.3
sdfds 3
sdfsdf 2.1
dsfsdf -1 

if x is 2

I want to print sdfsdf 2.1

How to express it in awk (bash or sed is fine too)

It's awfully tempting to do this:

sort -k 2 -g  | awk '$2 >= 2 { print; exit }'

Tested and works on your example. If no second column is at least 2, it prints nothing.

awk:

BEGIN {
  min=0
  mint=""
  threshold=2
}
{
  if($2 > threshold && ($2 < min || min == 0)) {
    min = $2
    mint = $1
  }
}
END
{
  print mint, min
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM