Shubhro
Shubhro

Reputation: 73

Replace a string from a particular line in shell script

I have a file which has a lot of information. The file may gets updated with time. My question is i have a text which is in a particular line ( line number is not fixed). The only identifier is starting of the line: Eg:

A=I love you Mary. B=I love you Suzi. C=I love you Jimmy D=I love you Mary and Jimmy.

Now here i want to change Mary with Maria only where the unique identifier is "A". I cannot do it with line number as A can be in any line. I dont want to change last line which also have the word Mary.

Upvotes: 0

Views: 569

Answers (1)

Jeff Schaller
Jeff Schaller

Reputation: 2546

The standard way to do it would be to ask sed to make the change only on lines that match the pattern. For example, so change the first "Mary" to "Maria" on lines that start with "A=":

sed '/^A=/s/Mary/Maria/' < input > output

To change all of the "Mary" text to "Maria" on lines that start with "A=":

sed '/^A=/s/Mary/Maria/g' < input > output

Some sed implementations support a -i flag to do "in-place" editing; what it really does is make the changes to a temporary file and then copy that temporary file over the original. With those sed implementations, you could make the change in-place with:

sed -i '/^A=/s/Mary/Maria/' input

Upvotes: 1

Related Questions