Print smallest integer from file using awk custom function?
MR ZenWiz
mrzenwiz at gmail.com
Sat Jan 9 17:09:51 UTC 2016
On Fri, Jan 8, 2016 at 6:23 AM, asad <a.alii85 at gmail.com> wrote:
> `awk` function looks like this in a file name `fun.awk`:
>
> {
>
> print f()
> }
> function f()
>
> {
>
>
> if(NR==1){s=$0}
>
>
> if($0<p)
>
> {s=$0}
>
> {p=$0}
>
> { return s}
>
> }
>
> The contents of `awk.write`:
>
> 1
> 23
> 32
>
> The `awk` command is:
>
> awk -f fun.awk awk.write
>
>
> but it print x3 times. why?
>
It is a bit tricky to tell what this is supposed to do since your
formatting has no black delineations.
However, your function will parse this way:
if (NR == 1) { s = $0; } # if there are no other records, save $0 in s
if ($0 < p) { s = $0; } # if the new value $0 is less than the
uninitialzied variable p, save $0 in s
{ p = $0; } # save $0 in p (why?)
{ return s; } # return the current value of the s
1. [Style/clarity] You don't need black delimiters "{" and "}" around
single line statements, though you can use them. They make reading
for actual blocks, like function bodies, tricky. A semicolon will do
(and should be used for clarity to the reader).
2. [Style/clarity] You don't need to return global variables from
subroutines, you can just use them.
3. [Function] You print the return value of function t for every input
line. If you just want a single output, put the print statement in an
END block.
HTH
MR
More information about the ubuntu-users
mailing list