bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] Efficient way to reverse a string


From: david kerns
Subject: Re: [bug-gawk] Efficient way to reverse a string
Date: Wed, 24 Apr 2019 23:21:43 -0700

I think he's asking in the context of an awk program...

I don't think you can get away from concat w/out using printf on each char,
maybe buffering will save you, but intuitively, I would expect better
performance out of concat on a string with one print at the end...

$ echo abcdefg 123 456 ABC | gawk '{n=split($0, a, "");for
(i=n;i>0;i--)printf("%s",a[i]);printf("\n")}'
CBA 654 321 gfedcba
$ echo abcdefg 123 456 ABC | gawk
'BEGIN{FS=""}{for(i=NF;i>0;i--)printf("%s",$(i));printf("\n")}'
CBA 654 321 gfedcba

I would expect these concat versions to perform better, but I leave that as
an exercise for the student ;)

$ echo abcdefg 123 456 ABC | gawk  'BEGIN{FS=""}{x="";for(i=NF;i>0;i--)x=x
$(i);print x}'
CBA 654 321 gfedcba

$ echo abcdefg 123 456 ABC | gawk '{n=split($0,a,"");for(i=n;i>0;i--)x=x
a[i];print x}'
CBA 654 321 gfedcba

in addition to the substr() example in your referenced post



On Wed, Apr 24, 2019 at 10:57 PM Peter Brooks <address@hidden>
wrote:

> Why not just use 'rev' - as an embedded command if you want the result in
> awk:
>
> $ echo the quick brown fox jumps over the lazy dog|rev
>
> god yzal eht revo spmuj xof nworb kciuq eht
>
>
> On Thu, 25 Apr 2019 at 05:06, Peng Yu <address@hidden> wrote:
>
> > Hi,
> >
> > The following way to reverse a string seems to be inefficient as it
> > involves multiple concatenations.
> >
> >
> >
> https://www.unix.com/shell-programming-and-scripting/223077-awk-reverse-string.html
> >
> > Is there a more efficient way to reverse a string? Thanks.
> >
> > --
> > Regards,
> > Peng
> >
> >
>
> --
> Peter Brooks
>
>
> Mobile: +27 82 717 6404
> Skype:  Fustbariclation
> Twitter: Fustbariclation
> Author Page: amazon.com/author/peter_brooks
>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]