w00t
w00t

Reputation: 676

sed replace inside a group/match

I have the following log line:

2017-01-01 Client:abc ID:144

I need to process it and insert it in MySQL, but sometimes the data might come wrong:

2017-01-01 Client:a, b .c ID:144

How can I perform a sed replace only inside the "Client:xxx" group so I can remove the unwanted characters?

Upvotes: 0

Views: 407

Answers (1)

SLePort
SLePort

Reputation: 15461

Using backreferences and t command, to capture and output only wanted characters between Client: and ID:

$ sed -r ':a;s/(Client:[^ ,.]*)[ ,.](.* ID)/\1\2/;ta;' <<< "2017-01-01 Client:a, b .c ID:144"
2017-01-01 Client:abc ID:144

All characters up to and excluding next unwanted character([ ,.]) are captured and output. The t(for test) command loops to the beginning of the script(to the :a label) if the substitution succeeds.

Upvotes: 1

Related Questions