awk script to "clamp" numbers.

Hello. I'm new to the command line and am self teaching how to use it. I have a .csv file that contains the following data:

5,10,15,30,8,3,9,10,11,3,12

I'm trying to write an awk script that will "clamp" a number that is > 10 to 10. (i.e. 30 will become 10 but 5 would stay as 5)
The output is to be as follows:

5
10
10
10
8
3
9
10
10
3
10

This is what I have so far but I don't know if I am even in the right ballpark. Any pointers?

BEGIN {
FS=","
}

{
for (i=0; i <= NF; i++)
  array = $1;

max=10;
print "output";

for (i=1; i <= NF; i++){
        if (array > max) {
                array = max;
}
}
}

END {
print array
}

Does it come close to what you expect?

Not at all. It just prints "Output" and then a single empty line. I was able to get it to print the first 5 but that was it

Try

awk -F, '
        {for (i=1; i <= NF; i++) print $i<10?$i:10
        }
' file
5
10
10
10
8
3
9
10
10
3
10
1 Like

Thanks, that does work. I was trying to learn how to code the solution in an awk script with Begin {} {} End{} and not using any of the built-in awk functions.

You didn't say so in your spec...

How about

awk '
BEGIN   {FS = ","
        }
        {for (i=1; i <= NF; i++)        {if ($i<10)     T = $i
                                           else         T = 10
                                         print T
                                        }
        }
' file
1 Like

Awesome. Thanks for all of your help. Quick question just for learning purposes. If I wanted to put the "print T" in the END {}, how would I do that. I put it in there and it just prints 10.

In my proposal, print T in a loop prints NF times. In the END section, it just prints once, the last value.

EDIT: You can have it in an END section like

awk '
BEGIN   {FS = ","
        }
END     {for (i=1; i <= NF; i++)        {if ($i<10)     T = $i
                                         else           T = 10
                                         print T
                                        }
        }
' file

But this works on the last line - in your sample the only line - only, and not all awk versions will keep the last line for the END section...