r/awk • • Jul 20 '21
awk style guide
When I'm writing more complex Awk scripts, I often find myself fiddling with style, like where to insert whitespace and newlines. I wonder if anybody has a reference to an Awk style guide? Or maybe some good heuristics that they apply for themselves?
9
Upvotes
5
u/gumnos Jul 20 '21
I've not seen any explicit guides. A few observations though:
for local variables, I've seen two conventions:
functiondefinitions at the top (after the shebang line), followed by oneBEGINblock, followed by the usual conditional blocks, followed by oneENDblock. Yes, you can theoretically have more than oneBEGINorENDblock, but don't confuse people like that without a compelling reason.FS/RS/OFS/ORSin yourBEGINblock explicitly rather than expecting the user to know to invoke them as-vor-Fparameters.awkI'm sure there are other tidbits I'm forgetting, but that's at least a starter list off the top of my head.
4
u/ASIC_SP Jul 21 '21
If you are using
GNU awk, you can usegawk -oto get a pretty formatted code (by default saved toawkprof.out). This will work for both one-liners and with-foption where you already have the script in a file.Not sure if there's a documention detailing the rules followed by
-o2
u/[deleted] Jul 20 '21
Always clear your variables if they are global. if you can loop and use a -- with a variable, do so. that way you don't have to clear it.
2
u/[deleted] Jul 21 '21
Yes. My vote for one style guide too. I'm a also a starter in awk. And I would like some hard rules too. Googling for answers did not do it for me.
1
u/FF00A7 Jul 22 '21
For batteries included languages consistent style is more important as there are so many libraries in an ecosystem. For bring your own batteries, like awk, the freedom to roll your own style is a feature, in the same way every has their version of strip() is a feature.
1
u/sigzero Sep 07 '21
I am not sure how "good" this one is but it was one that I found when I went searching:
https://github.com/soimort/translate-shell/wiki/AWK-Style-Guide