Home > Net >  Trying to find a maximum from a file in shellscript
Trying to find a maximum from a file in shellscript

Time:11-15

In shellscript, I'm trying to get the maximum value from different lines. There are 5 things in a line, and the fifth is the value, that I need to compare to the others in the lines. If I found, what the maximum is, then I have to write out the rest of the line too.

For example, this is 2 lines from the file. (there are more than these 2 of course)

47.6498634, 19.1404118, 2021.07.14., 13:04, 9

69.4206662, 12.3216747, 2021.08.21., 14:44, 20

Since 20 is bigger than 9, I'd have to write out the things from the second row. I've tried many things, but I always get some sort of an error.

I have to use #!/bin/sh !!!

Any advices how could I do it?

CodePudding user response:

Sort numerically, by field 5, then print only the line containing the highest value:

sort -nk5,5 data.txt | tail -n 1

CodePudding user response:

Try

< MYFILE sort -k5nr | head -1

< pipes MYFILE into sort, -k5 says to sort on the fifth key n is for numeric order, r sorts in reverse order so the largest number comes first. Then head -1 outputs only the first line. The end result is

69.4206662, 12.3216747, 2021.08.21., 14:44, 20

  • Related