Dylan Atkinson
Dylan Atkinson

Reputation: 13

Sed command replace number + letter with number + \n + letter

I have a (what I think is a tricky) sed problem.

I have a file which contains plain text and numbers.

Every instance in the file, where there is a number [0-9] followed by a letter which is either a C, T or D, I would like to replace it with the same number followed by a \n character and the same letter.

E.g.

551235D 4218789T 435151C

I would like to replace with

 551235\nD 4218789\nT 435151\nC

The problem I am facing is how to replace each letter/number combo with the same letter/number. It is easy to replace [0-9] followed by C, T or D with whatever I like, the problem is inserting a \n between the number and letter...

Any help would be greatly appreciated.

Upvotes: 0

Views: 1134

Answers (2)

kdhp
kdhp

Reputation: 2116

In sed, a newline can be substituded by escaping it with a \:

A line can be split by substituting a <newline> into it. The application shall escape the <newline> in the replacement by preceding it by a <backslash>.

Additionally, newlines can easily be added by arguments through multiple uses of -e:

The commands specified by each -e or -f option shall be added to the script in the order specified. When each addition is made, if the previous addition (if any) was from a -e option, a <newline> shall be inserted before the new addition.

Either of the above can be combined with back-reference substitution (\1, \2, etc.) to split lines between the desired characters.

$ sed 's/\([0-9]\)\([DTC]\)/\1\
> \2/g'

or

$ sed -e's/\([0-9]\)\([DTC]\)/\1\' -e'\2/g'

Upvotes: 0

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed  's/\([0-9]\)\([DTC]\)/\1\n\2/g' file

Use back references.

Upvotes: 2

Related Questions