views:

23

answers:

1

I know that usually you don't want one-liners/single commands to get too long but it seems like there's occasionally a longish one-liner that would benefit from replacing repetitive elements with a function.

Is it possible to use a short function chop down the length of your command?

For example there's no ceiling or round function to my knowledge built into awk, so you could 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 incorporate these functions into one liners?

e.g.

Could you use it in a script to get the ceiling of the 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 would be:

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

...and for the round function would be

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

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

+2  A: 

Just use a return statement in your function:

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

Functions are called by value rather than by reference, so changes in a variable's value do not affect the caller's variables.

Dennis Williamson
That worked perfectly! Thanks!!
Jason R. Mick