3

When looking for a quick way of right trimming a text string, I found the following wiki page:

Wiki trimming page

In the chapter about AWK it gives 2 sets of examples:

ltrim(v) = gsub(/^[ \t]+/, "", v)

rtrim(v) = gsub(/[ \t]+$/, "", v)

trim(v)  = ltrim(v); rtrim(v)

or

function ltrim(s) { sub(/^[ \t]+/, "", s); return s }

function rtrim(s) { sub(/[ \t]+$/, "", s); return s }

function trim(s)  { return rtrim(ltrim(s)); }

The lower example is entirely familiar and works fine, but the first example looks different to anything I have seen in 20 years of AWK programming. It looks like a really useful quick way to define and use a function in one line. I can't get this syntax to work in GNU Awk 3.1.5 - so is it something which was introduced in a more recent version?

I would be grateful of a real working example if anyone is familiar with this syntax.

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
piquet00
  • 31
  • 1
  • the first example is just pseudo-code. you have to use the second form for it to be legal awk-syntax. Should have been convenient though :-) – Fredrik Pihl Dec 08 '11 at 12:12

2 Answers2

2

I suppose this example is just wrong. The syntax

identifier(parameter) = ...

doesn't work with none of the variants I've tested: GNU awk (3, 4 - the latest for the moment), AT&T Bell's awk and mawk.

Just like calling an undefined function produces an error as expected as well.

Perhaps the author wanted only to illustrate the idea with pseudo-code?

Dimitre Radoulov
  • 27,252
  • 4
  • 40
  • 48
0

My understanding is the first set of examples doesn't define a function but just tells that the (missing) ltrim(s) function can be replaced by gsub(/^[ \t]+/, "", v), etc.

gsub is unnecessary by the way, sub would be enough like it is in the function alternative.

jlliagre
  • 29,783
  • 6
  • 61
  • 72