Saturday, November 13, 2021

[SOLVED] sed, insert whitespace at the Nth position after a delimiter

Issue

I am not very fluent using bash especially the sed command: I am trying to use sed to insert another whitespace at the 2nd position after each whitespace in the following string:

Id_26300, 0404 0202 0202 0202

in order to obtain:

Id_26300, 04 04 02 02 02 02 02 02

and I need to do this in my whole text file from line 3 to the end:

FileName
InfoField A B C D
Id_26300, 04 04 02 02 02 02 02 02
Id_26301, 02 02 02 04 02 04 02 02
...

I tried to find a solution but could not... Thank you so much for your help!


Solution

Given the limited input:

sed '3,$s/ ../& /g'

From line 3 to the end of the file 3,$, match a space followed by any 2 characters ... Use & to mean "what was matched" and add a space after it. Use g to do repeatedly.



Answered By - stevesliva