Replace particular words in file based on if finds another words in that line

Hi All,

I need one help to replace particular words in file based on if finds another words in that file .

i.e.

my self is peter@king.
i am staying at north sydney.
we all are peter@king.

How to replace peter to sham if it finds @king in any line of that file.

Please help me out.:confused:

Hello Rajib Podder,

Welcome to forums, please use CODE TAGS as per forum rules for commands/codes/Inputs you are posting into your post. Coming to your question now, could you please try following and let me know if this helps you.

awk '{gsub("peter@king","sham@king")} 1'  Input_file

Let me know if you have any queries on same.

Thanks,
R. Singh

Hi R,

Thanks for your help.

But if it like below format

my self is peter.<variable>@king then how to change only peter to sham based on @king.
i.e.

myself is peter.r1@king
myself is peter.r2@king
myself is peter.r3@king
myself is peter.r4

ouput should be :

myself is sham.r1@king
myself is sham.r2@king
myself is sham.r3@king
myself is peter.r4

is it possible

Hello Rajib Podder,

To thank any person in forums, you could HIT THANKS button at left corner of each post. Also please use CODE TAGS for your shown sample Inputs. Could you please try following and let me know if this helps you.

awk '/peter.*@king/{sub("peter","sham")} 1'  Input_file

Output will be as follows.

myself is sham.r1@king
myself is sham.r2@king
myself is sham.r3@king
myself is peter.r4

Thanks,
R. Singh

1 Like

Hi Ravi,

But the output should include sham.r1 also etc.It is not visible

---------- Post updated 10-06-17 at 12:05 AM ---------- Previous update was 10-05-17 at 11:59 PM ----------

Hi Ravi,

I think you got my point.

Regards,
Rajib

Hello Rajib Podder,

You could try following sed command too for same.

sed  '/peter.*@king/s/peter/sham/g'

Thanks,
R. Singh

1 Like

Hi Ravi,

It is working perfectly now.One more question,can we add multiple condition and multiple replacement on same command.

Regards,
Rajib

Yes, we could do multiple conditions in a single command. If you have questions feel free to ask(if different may be in a new thread), request you to take sometime to write your post and use CODE TAGS(see my post how commands are different than text that is because of code tags). Let me know if you have any queries.

Thanks,
R. Singh

1 Like

Hi Ravi,

Definitely I will do that .

Regards,
Rajib