LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Print smallest integer from file using awk custom function? (https://www.linuxquestions.org/questions/linux-software-2/print-smallest-integer-from-file-using-awk-custom-function-4175563409/)

lazer00 01-08-2016 09:10 AM

Print smallest integer from file using awk custom function?
 
`awk` function looks like this in a file name `fun.awk`:

Quote:

{
print small()
}
function small()

{
a[NR]=$0

smal=0

for(i=1;i<=3;i++)
{
if( a[i]<a[i+1])

smal=a[i]

else

smal=a[i+1]

}
return smal
}
The contents of `awk.write`:

Quote:

1
23
32
The `awk` command is:

awk -f fun.awk awk.write

It gives me no result? Why?

berndbausch 01-08-2016 10:04 AM

Use a simpler program, e.g.
Code:

NR==1 || $1 < minimum { minimum = $1 }
END { print minimum }

This assumes that the first field of each record is the number we check, and that all numbers are 0 or positive. It's not tested.

lazer00 01-08-2016 12:05 PM

Quote:

Originally Posted by berndbausch (Post 5475042)
Use a simpler program, e.g.
Code:

NR==1 || $1 < minimum { minimum = $1 }
END { print minimum }

This assumes that the first field of each record is the number we check, and that all numbers are 0 or positive. It's not tested.

thanks for the one liner but can this code be translated to a function?

berndbausch 01-08-2016 06:27 PM

It would be rather different, clumsy and un-awk-ish. Why do you insist on a function?

And what is that function's specification - input and output?

Let me elaborate why I think a function is the wrong solution. awk programs consist of pattern-action pairs which work on one line at a time. Users can define functions for better structuring their actions.
Your task requires processing the entire file. While that is possible inside a single awk action, for instance using the built-in function getline, it's against awk's nature. It will also be hard to read compared to my two-line program.


All times are GMT -5. The time now is 03:26 AM.