Talk About Network



Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > Awk > Re: Indexed ass...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 6 Topic 2177 of 2236
Post > Topic >>

Re: Indexed assignment

by Ed Morton <morton@[EMAIL PROTECTED] > Mar 3, 2008 at 06:14 AM

On 3/3/2008 4:42 AM, bernhard.strohmeier@[EMAIL PROTECTED]
 wrote:
> Hi,
> 
> Is it possible in AWK to assign a string by index into another string?
> I am looking for something like the subst() function in SQL.
> 
> For example, if I would like to insert the string "abc" into the
> string "12345789", starting at position 3 overwriting the other
> elements the required result would be "12abc6789"
> 
> Thanks in advance.

It's not pretty, but in GNU awk:

$ gawk --re-interval 'BEGIN{orig=123456789; rep="abc";
print gensub("(.{2}).{"length(rep)"}","\\1"rep,"",orig)}'
12abc6789

The "{2}" tells it how many characters to start AFTER as opposed to FROM.
You
may prefer:

$ echo 123456789 |
gawk --re-interval 'BEGIN{rep="abc"; pos=3;
pat="(.{"pos-1"}).{"length(rep)"}"}
{print gensub(pat,"\\1"rep,"")}'
12abc6789

so you can specify a FROM value and avoid calling length() for every
record or:

$ echo 123456789 | awk --re-interval -v rep="abc" -v pos=3
'BEGIN{pat="(.{"pos-1"}).{"length(rep)"}"}
{print gensub(pat,"\\1"rep,"")}'
12abc6789

so you can pass the replacement string and starting point from your OS
or....

Regards,

	Ed.




 6 Posts in Topic:
Indexed assignment
bernhard.strohmeier@[EMAI  2008-03-03 02:42:46 
Re: Indexed assignment
gazelle@[EMAIL PROTECTED]  2008-03-03 11:34:00 
Re: Indexed assignment
Ed Morton <morton@[EMA  2008-03-03 06:14:11 
Re: Indexed assignment
Joel Reicher <joel@[EM  2008-03-03 12:32:32 
Re: Indexed assignment
Joel Reicher <joel@[EM  2008-03-04 02:55:25 
Re: Indexed assignment
bernhard.strohmeier@[EMAI  2008-03-03 05:23:48 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sat May 17 1:38:03 CDT 2008.