Mercer
Mercer

Reputation: 9986

How to use sed to replace only the first occurrence?

This is my command:

sed -i -E  's/(<Connector port=)([a-zA-Z0-9"-])+/\1"VALUE10"/g' server.xm

When i execute this cAll occurrences have been replaced in the file.

How to use sed to replace only the first occurrence in my file?

Upvotes: 0

Views: 916

Answers (2)

Ed Morton
Ed Morton

Reputation: 203149

Just use awk. With GNU awk for gensub() and inplace editing:

awk -i inplace '!f{$0=gensub(/(<Connector port=)[[:alnum:]"-]+/,"\\1\"VALUE10\"","g"); f=1} 1' server.xm

Upvotes: 1

Jack
Jack

Reputation: 6158

Find the first occurrence in the file:

first=$( egrep -n 'Connector port=[a-zA-Z0-9"-]' server.xm | head -1 | cut -d: -f1 )

Then, replace on that line:

sed -i -E "${first}s/(<Connector port=)([a-zA-Z0-9\"-])+/\1\"VALUE10\"/g" server.xm

Upvotes: 0

Related Questions