Need you assistance in AWK

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Need you assistance in AWK

Sara
Hi Guru,

First I have to say thank you for your posts in UNIX School, all are very helpful.  I have learned a lot from your blog.

I need you assistance in AWK:

echo "abcdefghijklmnopqrstuvwx" | sed 's/…./&:/4'
output- abcdefghijklmnop:qrstuvwx – I have inserted ':' in the fourth occurrence of the search pattern '….'.

I’m trying the same using AWK but I couldn’t figure out. I’m just started learning AWK and I didn’t understand how to retrieve the nth occurrence using AWK.

Could you please tell me how to retrieve the nth occurrence using AWK?

Thanks in advance,
Sara
Reply | Threaded
Open this post in threaded view
|

Re: Need you assistance in AWK

Guru
Administrator
This post was updated on .
Hi Sara
    Thanks for your feedback on the articles. Regarding the question:  sed and awk are very different, though some requirements have simple solutions in both awk and sed. However, in many cases, its not so because they both are primarily meant for different things.

   For your question, sed is the ideal candidate, not awk since expression handling in awk is not that great. Anyways, the answer in awk is as below:


$ echo "abcdefghijklmnopqrstuvwx" | awk '{for(i=1;i<length;i+=4){j++;printf substr($0,i,4);if(j==4)printf ":";}}'
abcddefghijklmnop:qrstuvw

Guru.
Reply | Threaded
Open this post in threaded view
|

Re: Need you assistance in AWK

Sara
Understand. Thank you Guru.

Regards,
Sara