internal buffer in awk

internal buffer in awk

am 28.01.2008 19:30:39 von Oxyopes

Hi friends,
vi has internal buffer to substitute matches like:

:%s#a\(.\)c#the midle character was \1#

I'd like to do similar with awk. Example, if awk had a similar buffer
system as vi, then i want that:

echo abc | awk ' /a\(.\)c/ {print "the midle character was "\1 } '

Is there an option like that in awk?
Thanks in advance ...

Re: internal buffer in awk

am 28.01.2008 19:48:09 von Janis Papanagnou

Oxyopes@googlemail.com wrote:
> Hi friends,
> vi has internal buffer to substitute matches like:
>
> :%s#a\(.\)c#the midle character was \1#
>
> I'd like to do similar with awk. Example, if awk had a similar buffer
> system as vi, then i want that:
>
> echo abc | awk ' /a\(.\)c/ {print "the midle character was "\1 } '
>
> Is there an option like that in awk?

I don't recall to have heard of that in awk.

> Thanks in advance ...

In your simple case you could do a match() call and use substr() with
RSTART and RLENGTH as a workaround.

Janis

Re: internal buffer in awk

am 28.01.2008 19:55:59 von Stephane CHAZELAS

On Mon, 28 Jan 2008 10:30:39 -0800 (PST), Oxyopes@googlemail.com wrote:
[...]
> vi has internal buffer to substitute matches like:
>
> :%s#a\(.\)c#the midle character was \1#
>
> I'd like to do similar with awk. Example, if awk had a similar buffer
> system as vi, then i want that:
>
> echo abc | awk ' /a\(.\)c/ {print "the midle character was "\1 } '
>
> Is there an option like that in awk?
[...]

That's the one thing that is missing most from awk (a big
mistake of their authors in my opinion).

gawk has it with gensub(). Othewise, as another poster
mentionned, you need to do convoluted stuff with match(), RSTART
and RLENGTH.

....or you could use perl instead of awk.

perl -nle 'print "the middle character was $1" if /a(.)c/'

(or sed of course)

--
Stephane

Re: internal buffer in awk

am 28.01.2008 21:34:59 von Ed Morton

On 1/28/2008 12:30 PM, Oxyopes@googlemail.com wrote:
> Hi friends,
> vi has internal buffer to substitute matches like:
>
> :%s#a\(.\)c#the midle character was \1#
>
> I'd like to do similar with awk. Example, if awk had a similar buffer
> system as vi, then i want that:
>
> echo abc | awk ' /a\(.\)c/ {print "the midle character was "\1 } '
>
> Is there an option like that in awk?
> Thanks in advance ...

Only with GNU awk:

$ echo abc | gawk '{print "the middle character was",gensub(/a(.)c/,"\\1","")}'
the middle character was b

or:

$ echo abc | awk '{$0=gensub(/a(.)c/,"the middle character was \\1","")}1'
the middle character was b

but you should use sed instead of awk for simple substitutions:

$ echo abc | sed 's/a\(.\)c/the middle character was \1/'
the middle character was b

If you're trying to do anything more complicated, then use awk but maybe there's
a better way to accomplish what you really want.

Ed.