-1

I am trying find and replace the line one of the existing file, when I am running the below sed command it is replacing all the lines which have the matched string, but instead I want to change only one place inside the file.

sed -i 's/azure.com/test.com/' file_name

Actual file

server_name azure.com
server_name azure.com

Expected result

server_name test.com
server_name azure.com
tripleee
  • 175,061
  • 34
  • 275
  • 318
Anonymuss
  • 381
  • 1
  • 7
  • 19
  • 2
    Does this answer your question? [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) – Dabombber Aug 18 '20 at 06:12

2 Answers2

1

You can do this with portable sed with a simple loop.

sed '/azure\.com/{
    s//test.com/
    :a
    n
    ba
}' file

When you see a match, substitute; then start a loop which simply consumes and prints the rest of the file.

This is significantly less obscure in Awk. If you have GNU Awk, you even have an -i inplace option which behaves like sed's -i option.

awk '/azure\.com/ && !p { sub(/azure.com/, "test.com"); p=1 }' file
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

Try this:

sed -i "0,/ azure.com: /{s/ azure.com/ test.com/}" file_name 

It will replace only the first occurrence of azure.com from the file.

tripleee
  • 175,061
  • 34
  • 275
  • 318