sodiumnitrate
sodiumnitrate

Reputation: 3143

Sed add line in between two characters on each line

I have a file with the following lines:

HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX O   ...
HETATM XXXX O   ...
HETATM XXXX O   ...

where XXXX is a number with 1-5 digits. I would like to add a space in between XXXX and O in the last three lines, so that they match the first three. I can select the relevant part with HETATM *[0-9]* O. How can I add an extra space in between [0-9]* and O with sed? (Note: I'm using Mac OS X)

Upvotes: 0

Views: 33

Answers (1)

fedorqui
fedorqui

Reputation: 290455

I would use tac to print the file in reverse, then awk to include a space after the 2nd field on the first three lines and then reverse it back:

tac file | awk 'NR<=3 {$2=$2" "}1' | tac

Test

$ cat a
HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX O   ...
HETATM XXXX O   ...
HETATM XXXX O   ...
$ tac a | awk 'NR<=3 {$2=$2" "}1' | tac
HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX  O   ...
HETATM XXXX  O ...
HETATM XXXX  O ...
HETATM XXXX  O ...

Upvotes: 2

Related Questions