Alfred Zhong
Alfred Zhong

Reputation: 7081

substitue part of a string using sed

Assume the regular expression of a email is [a-zA-Z0-9]+@[a-zA-Z0-9]+.[a-zA-Z0-9]+, I would like to substitute all the id part into "customer", for example

[email protected] => [email protected] [email protected] => [email protected]

I can write something like

$ echo [email protected] | sed 's/[a-zA-Z0-9][a-zA-Z0-9]*@[a-zA-Z0-9][a-zA-Z0-9]*\.[a-zA-Z0-9][a-zA-Z0-9]*/customer/g' 

But how can I get the domain part not changed? Basically, the question is find a pattern in a string and substitute just part of it and the remaining part not changed.

Upvotes: 0

Views: 153

Answers (2)

twalberg
twalberg

Reputation: 62379

I think you're making it too complicated:

echo [email protected] | sed -e 's/.*@/customer@/'

Upvotes: 1

that other guy
that other guy

Reputation: 123470

You can capture parts of the matched pattern with \(..\) and reuse it in your replacement string using \1:

echo [email protected] | sed 's/[a-zA-Z0-9][a-zA-Z0-9]*@\([a-zA-Z0-9][a-zA-Z0-9]*\.[a-zA-Z0-9][a-zA-Z0-9]*\)/customer@\1/g'

Upvotes: 1

Related Questions