Glad
Glad

Reputation: 341

Substitute pattern on a line containing another pattern

says file has

ABC DEF ,No
IMD DEF ,NO
ANC KOJD ,NO
ABC MSL ,NO

How do I use sed to substitute ,No with XYZ,No only on lines containing ABC?

So final output is

ABC DEF XYZ ,No
IMD DEF ,NO
ANC KOJD ,NO
ABC MSL XYZ,NO

Upvotes: 0

Views: 34

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed '/ABC/s/,no/XYZ &/i' file

This caters for all cases of no, however if the you want to cater for only No or NO use:

sed '/ABC/s/,N[oO]/XYZ &/' file

Upvotes: 0

fedorqui
fedorqui

Reputation: 289535

Use:

sed -r '/ABC/s/(,N[oO])/XYZ\1/' file

This uses sed '/pattern/s/find/replace/' file, which does the replacement s/find/replace/ in all lines containing pattern.

In this case, we catch ,No because it can be either upper or lowercase, so that it is printed back.

Test

$ sed -r '/ABC/s/(,N[oO])/XYZ\1/' a
ABC DEF XYZ,No
IMD DEF ,NO
ANC KOJD ,NO
ABC MSL XYZ,NO

Upvotes: 1

Related Questions