RohithSriram
RohithSriram

Reputation: 3

Sed-Replace immediate next string word coming after a particular pattern but only the first occurrence in a file

I need a sed command which will replace the string immediately after the pattern but only for the first occurrence in a file

For replacing first occurrence this was given:

sed -i '' -e '0,/abc/s//def/' filename

This will replace the matching string and not string after match

For replace string immediate after match this was given:

sed -i 's/\(text=\)\(.*\)/\1qwerty/' filename

This will replace string after immediate next to match but will do for all occurences.

In a file I have the string "text=abc" twice times like this:

abc
text=occurrence1
qwe
uio
text=occurrence2
dsf

I want to replace the occurence1 part with the string "qwerty" so that output looks like:

text=qwerty.

But I want to do this only for the first occurence in the file and not all places.

Upvotes: 0

Views: 1465

Answers (2)

Rohith S
Rohith S

Reputation: 110

Try this:

r="qwerty"

sed -i '' -e "1,/text=/s/\(text=\).*/\1${r}/" filename

This is as simple it can get.

Upvotes: 0

ashish_k
ashish_k

Reputation: 1581

With GNU sed should work:

Example:

cat file:
abc
text=xyz1
qwe
uio
text=xyz
dsf

Now, to replace only the first occurrence of string "text=" with "text=qwerty":

sed -r '0,/text=/{s/text=(.*)/text=qwerty/}' file

Output:

abc
text=qwerty
qwe
uio
text=xyz
dsf

Option '-r' in sed:

-r  : --regexp-extended, to use extended regular expressions

Upvotes: 1

Related Questions