How do you enable short functions in Awk One-Liners / Single Commands?

I know that usually you don’t want single-line / single teams to get too long, but it seems that sometimes there is a long single-line liner that will benefit from replacing repeating elements with a function.

Is it possible to use a short function that reduces the length of your command?

For example, there is no ceiling or round function, which, as far as I know, is built into awk, so you can write functions

'function round(a){a=(a < int(a)+0.5) ? int(a) : int(a+1)}'

and

'function ceil(a){a=(a == int(a)) ? a : int(a)+1}'

Could you include these features in one liner?

eg.

Could you use it in a script to get the ceiling of a file

$ cat money.data
121.52 133.45 136.77 155.22
132.11 141.30 12.78 78.98
31.21 149.03 33.50 84.67

... which for the ceiling function will be:

$ tail money.data
122 134 137 156
133 142 13 79
32 150 34 85

... and for the round function will be

$ tail money.data
122 133 137 155
132 141 13 79
31 149 34 85

I played with random awk statements, but couldn't figure out how to incorporate functions into one liner ...

+3
1

return :

function round(a){return (a < int(a)+0.5) ? int(a) : int(a+1)}
{for (f=1;f<=NF;f++) print round($f)}

, , .

+3

Source: https://habr.com/ru/post/1764559/


All Articles