AWK - find min value of each row with arbitrary si

2020-02-13 04:14发布

I have a file with the lines as:

5 3 6 4 2 3 5
1 4 3 2 6 5 8
..

I want to get the min on each line, so for example with the input given above, I should get:

min of first line:  2
min of second line: 1
..

How can I use awk to do this for any arbitrary number of columns in each line?

标签: awk min
2条回答
一夜七次
2楼-- · 2020-02-13 04:33

Your problem is pretty simple. All you need to do is to define a variable min in the BEGIN part of your script, and at each line, you just have to perform a simple C-like algorithm for minimum element (set the first field as min, and then perform a check with the next field, and so on until you reach the final field of the line). The total number of fields in the line will be known to you because of the variable NF. So its just a matter of writing a for loop. Once the for loop is fully executed for the line, you will have the minimum element with you, and you could just print it.

查看更多
We Are One
3楼-- · 2020-02-13 04:38

If you don't mind the output using digits instead of words you can use this one liner:

$ awk '{m=$1;for(i=1;i<=NF;i++)if($i<m)m=$i;print "min of line",NR": ",m}' file
min of line 1:  2
min of line 2:  1

If you really do want to count in ordinal numbers:

BEGIN {
    split("first second third fourth",count," ")
}
{
    min=$1
    for(i=1;i<=NF;i++)
    if($i<min)
        min=$i

    print "min of",count[NR],"line: \t",min
}

Save this to script.awk and run like:

$ awk -f script.awk file
min of first line:    2
min of second line:   1

Obviously this will only work for files with upto 4 lines but just increase the ordinal numbers list to the maximum number you think you will need. You should be able to find a list online pretty easily.

查看更多
登录 后发表回答