AWK - find min value of each row with arbitrary size

自闭症网瘾萝莉.ら 提交于 2019-11-29 12:47:29

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!