Aaron Perry Aaron Perry - 1 year ago 63
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.



Expected Output:

97 100 101 101 102 101

Attempted Code:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download