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.

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 :-) Commented Dec 8, 2011 at 12:12

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I see - yes that makes sense. Thank you for taking the time to test.
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.

1 Comment

Yes, on a second read, I think that your understanding is correct. Often we're too literal :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.