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.


|