0

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?

Mercer
  • 9,736
  • 30
  • 105
  • 170
  • 1
    Possible duplicate of [How to use sed to replace only the first occurrence in a file?](https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file) – Benjamin W. May 23 '17 at 14:55

2 Answers2

1

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
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

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
Jack
  • 5,801
  • 1
  • 15
  • 20