0
41703
10002
30003
40002
40000
20203
20203
30100
50000
50000
50000
50000
70700
70600

I have this file. and i Want output as

4.17.3
1.0.2
3.0.3
4.0.2
4.0.0
2.2.3
2.2.3
3.1.0
5.0.0
5.0.0
5.0.0
5.0.0
7.7.0
7.6.0

I'm working on solaris machine.

3
$ sed -e 's/\(.\)\(..\)\(..\)/\1.\2.\3/' -e 's/\.0/./g' file
4.17.3
1.0.2
3.0.3
4.0.2
4.0.0
2.2.3
2.2.3
3.1.0
5.0.0
5.0.0
5.0.0
5.0.0
7.7.0
7.6.0

The first sed substitution creates x.yy.zz from xyyzz. It does this by capturing the three groups of characters in separate capture groups (the \(.\) and the two \(..\) where each dot matches a single character), and then inserts these again with dots in-between.

The second substitution removes any zero immediately after a dot.

  • Perfect!!!!! That's the thing which was all i needed..But need one explaination. Can you explain how first sed is converting xyyzz -> x.yy.zz pattern? – acroniks Mar 23 '18 at 5:00
  • @UtkarshMishra See updated answer. – Kusalananda Mar 23 '18 at 6:36
4

Awk solution:

awk '{ printf "%d.%d.%d\n", substr($1,1,1), substr($1,2,3)/10, substr($1,5) }' file
  • substr(string, start [, length ]) - Return a length-character-long substring of string, starting at character number start.

The output:

4.17.3
1.0.2
3.0.3
4.0.2
4.0.0
2.2.3
2.2.3
3.1.0
5.0.0
5.0.0
5.0.0
5.0.0
7.7.0
7.6.0

If GNU awk is supported a shorter way would be as follows:

awk -v FS="" '{ print $1, ($2$3$4)/10, $5 }' OFS='.' file
  • FS="" - If the value is the null string (""), then each character in the record becomes a separate field.
  • 1
    With GNU awk I guess one could also set the fieldwidths explicitly e.g. gawk '{printf("%d.%d.%d\n",$1,$2,$3)}' FIELDWIDTHS='1 2 2' file – steeldriver Mar 22 '18 at 12:14
  • @steeldriver, yes, that would also be a good alternative – RomanPerekhrest Mar 22 '18 at 13:06
0

GNU sed solution

sed -r 's/\B(..)/.\1./; s/\.0/./g' input.txt

\B - Matches everywhere but on a word boundary; that is it matches if the character to the left and the character to the right are either both “word” characters or both “non-word” characters.

The sed solution without GNU features

sed -r 's/(.)(..)/\1.\2./; s/\.0/./g' input.txt

Output

4.17.3
1.0.2
3.0.3
4.0.2
4.0.0
2.2.3
2.2.3
3.1.0
5.0.0
5.0.0
5.0.0
5.0.0
7.7.0
7.6.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.