$ add="20010db885a3000000008a2e03707334"
$ echo $add
20010db885a3000000008a2e03707334
Required output: Insert a colon ':' after every 4 characters in the above line.
So the output required:
2001:0db8:85a3:0000:0000:8a2e:0370:7334
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

4 comments:
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'
@Mahesh, thanks. I never knew that. Thanks for the one liner.
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
@wecbxxx, do you mean this ?
$ echo $add | sed 's/...../&:/g;s/:$//'
20010:db885:a3000:00000:8a2e0:37073:34
Please let me know if your query was different; thanks
Post a Comment