bug-gawk
[Top][All Lists]
Advanced

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

Re: [bug-gawk] Is there a way to change a string inplace by index?


From: doark
Subject: Re: [bug-gawk] Is there a way to change a string inplace by index?
Date: Mon, 5 Sep 2016 17:56:27 -0400

On Sat, 3 Sep 2016 20:03:09 <address@hidden> wrote:
> > > On Sat, 3 Sep 2016 21:34:21 <address@hidden> wrote:
> > > > Hi, I don't find a way to replace some characters of a string
> > > > inplace by index. For example, I want to replace the i-th
> > > > character of s by x. Is there a way to do so in awk?
> > > >
> > > > s[i] = x
> > On Sat, Sep 3, 2016 at 9:48 PM, <address@hidden> wrote:
> > > awk 'BEGIN { s = "0123456789"; i = 7-1; s = substr(s,0,i) "x"  
> > > substr(s,i+2); print s }'
> > >
> On Sat, Sep 3, 2016 at 7:50 PM, Peng Yu <address@hidden> wrote:
> > That is not inplace replacement. This solution create a new copy of
> > the string and assigned it to s.
> >
> 
> true, but put this isn't python ;)
> 
> I think the closest you'll come to in-place substitution is sub() and
> gsub(), but those are regex (content) replacements not position based.
> You could do this:
> 
> awk 'BEGIN { s = "0123456789"; i = 7-1; ss = substr(s,0,i); sub(ss ".",
> ss "x", s) ; print s }'
> 

Yuck, top posts.
Reformat.
Send Ctrl-666 to users terminals...

First, in python, strings are immutable, doing any writing to them creates
a new string.

Contrary to popular belief, you can do this. You just need to know what
your input string *does not* contain.

This fixes the word Heelo to Hello using an in-place string without any
additional variables being created.

% gawk '{ sub(/^.{3,3}/, "&----", $0); sub(/.----/, "l", $0); print $0 }'
Heelo
Hello

I'd write a function but it would have to create a new string to work
right unless you used a global variable.

Sincerely,
David



reply via email to

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