Aaron Perry Aaron Perry - 5 months ago 9
Linux Question

Insert a space after the second character followed by every three characters

I need to insert a space after two characters, followed by a space after every three characters.

Data:

97100101101102101


Expected Output:

97 100 101 101 102 101


Attempted Code:

sed 's/.\{2\}/& /3g'

Answer

In two steps:

$ sed -r -e 's/^.{2}/& /' -e 's/[^ ]{3}/& /g' <<< 97100101101102101
97 100 101 101 102 101 

That is:

  • 's/^.{2}/& /'
    catch the first two chars in the line and print them back with a space after.

  • 's/[^ ]{3}/& /g'
    catch three consecutive non-space characters and print them back followed by a space.

Comments