insert zero before single numbers using sed (or awk)
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
insert zero before single numbers using sed (or awk)
I have been banging my head and googling for about a week trying various things and cannot come up with a solution. So, I would really appreciate any assistance.
I need to add a zero before a single number surrounded by period. For example:
10.4.256.14.3 would need to be converted to 10.04.256.14.03
3.4 would need to be converted to 3.04
I cannot just add a zero before all numbers, only the 'single' digits surrounded by periods.
Here is what I have so far:
Code:
#!/bin/bash
ONE=10.4.256.14.3
TWO=$(echo $ONE | sed -e 's/\.\([0-9]\)\./\.0\1\./g')
echo $TWO
The output is:
10.04.236.14.3
It works for the first single number, the '4' but not for the second single number, the '3' at the end. I know the problem is the use of the \1 but I am using that because I need to 'keep' the number matched by [0-9] so I can stick it back in after inserting the 0. I hope this makes sense.
Yeah, unfortunately, they don't. That's why I used the two examples, one with 5 'columns' and one with 2. There is no pattern to either the number of columns or the number of digits in any particular column.
Thanks, everybody, for the excellent help. Several of these solutions seem to work just fine. I'm testing out Kenhelm's solution in my script and so far so good.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.