Thursday, September 24, 2009

Insert after certain characters - awk and sed

$ add="20010db885a3000000008a2e03707334"
$ echo $add

Required output: Insert a colon ':' after every 4 characters in the above line.
So the output required:


Using awk:

$ echo $add | awk -F "" '
{for(i=1;i<=NF;i++){printf("%s%s",$i,i%4?"":":")}}'|awk '{sub(/:$/,"")};1'

Note: Mind the use of "" as the field separator.

Using sed:

$ echo $add | sed 's/..../&:/g;s/:$//'

Related post:

- Break a line into multiple lines using awk and sed


Mahesh Kharvi said...

field sepearation with "" doesn't work with NON-GNU awk.

below code should work with all types of awk.

echo $add | awk '{for(i=1;i<=length($0);i+=4){printf("%s:",substr($0,i,4))}}'|awk '{sub(/:$/,"")};1'

Jadu Saikia said...

@Mahesh, thanks. I never knew that. Thanks for the one liner.

wecbxxx said...

hi i got a question. i try to use this but what happens if i try to insert ":" in the text not by 4 in 4. i try to do it by 5 then 8 an the 10 in order or other number o characters

Jadu Saikia said...

@wecbxxx, do you mean this ?

$ echo $add | sed 's/...../&:/g;s/:$//'


Please let me know if your query was different; thanks

Geo Ghe said...

Hello Sir!

I have a text line like this:
20100131142315 Constanta 0.0869

I want to look like this:
2010 01 31 14:23:15 0.0869

So please help me.

Thank you very much in advance

Jadu Saikia said...

@Geo Ghe, thanks for the question. You can use awk substr function for this purpose, something like:

$ echo "20100131142315 Constanta 0.0869" | awk '{
printf ("%s %s %s %s:%s:%s %s\n", one, two, three, four, five, six, $NF)

2010 01 31 14:23:15 0.0869

You can refer to this post of my blog

hope this helps.

Anbu said...

echo $add | awk ' gsub("....","&:") '

© Jadu Saikia