Awk/sed - add space between dot and letter

I need to change

[A-Z].[A-Z]

into

[A-Z]. [A-Z]

so that e.g.

A.J

becomes

A. J

I have tried

sed 's/[A-Z]\.[A-Z]/[A-Z]\.\ [A-Z]/g'

but that didn't work.

sed 's/\([A-Z]\)\.\([A-Z]\)/\1. \2/g'

\1 is the 1st matching \(...\) etc.

1 Like

Hi,

you can use this also.

sed "s/\./\. /g" $file

Reason: replace the "." with ". "

But here the task is to replace "." when prefixed and followed by an uppercase character.
Test:

echo ...A.1.B.C.D.E.FX. | sed 's/\([A-Z]\)\.\([A-Z]\)/\1. \2/g'

...A.1.B. C.D. E.FX.
You further see how the /g modifier works. It repeats the expression on the remainder of the line, after the part that was covered by the previous expression.
If the repetition should include the last character of the previous expression, things become complicated. In this case one can run the whole statement twice:

echo ...A.1.B.C.D.E.FX. | sed 's/\([A-Z]\)\.\([A-Z]\)/\1. \2/g; s/\([A-Z]\)\.\([A-Z]\)/\1. \2/g'

...A.1.B. C. D. E. FX.

Hey,

you can use this also.

#iterating the sed command up to end
echo ...A.1.B.C.D.E.FX. | sed -e :a -e 's/\([A-Z]\{1\}\)\.\([A-Z]\{1\}\)/\1\. \2/;ta'
...A.1.B. C. D. E. FX.
1 Like

Thanks for the hint!
The explicit loop is certainly more efficient.

echo ...A.1.B.C.D.E.FX. | sed -e :a -e 's/\([A-Z]\)\.\([A-Z]\)/\1. \2/;ta'

Nice solution indeed. But you don't necessarily need the two expressions (may depend on the sed version used?),

$ echo ...A.1.B.C.D.E.FX. | sed ':a;s/\([A-Z]\)\.\([A-Z]\)/\1. \2/;ta'
...A.1.B. C. D. E. FX.

will do as well.

Old Unix sed wants the :label on one line, either

sed '
:label
other stuff
'

or

sed -e :label -e 'other stuff'

GNU sed has it fixed.

1 Like

Oooh, got you! Thanks!

perl -pe 's/[A-Z]\.(?=[A-Z])/$& /g'
1 Like