Home > Back-end >  How to replace text in a string through powershell?
How to replace text in a string through powershell?

Time:11-17

Suppose I have a file(local.tfvars) which consists of:

Car {  
}  
Bus {
}

Now I want to replace car in this file with

Car {
  Audi,
  Mercedes,
}  
Bus {
}

through the script.

I am fetching the local file through

 $localfile = Get-Content -Path ("local.tfvars")          

after that I am using:

  $localfile.replace("Car","Car{`n Audi,Mercedes)     

Which should give me the output as:

Car {
  Audi,  
  Mercedes,
}
Bus {
}

But the output doesn't seem to come in this way, the output that I am getting is:

Car {
  Audi,
}
Bus {  
}
Car {
  Mercedes,
}
Bus { 
}

See here these are getting printed twice which I don't want.

CodePudding user response:

Maybe this is what you're looking for?

$result = @'
{

Car {
}
Bus {
}

}
'@

$result = $result.Replace("Car {", "Car {`r`nAudi,`r`nMercedes,`r")

$result

CodePudding user response:

Although your example looks like JSON, it is not, so what you can do here is to read the file as single multiline string and use regex operator -replace on its content.

The easies way to retain the replacement's (multiline) format is by using a Here-String:

# replace with
$newCars = @'
Car {
  Audi,
  Mercedes,
} 
'@

# find the empty Cars node and replace it with above $newCars
# if you also want the output on screen, append switch `PassThru` to the Set-Content command
(Get-Content -Path "local.tfvars" -Raw) -replace '(?m)^Car\s*\{\s*}', $newCars | Set-Content -Path "local.tfvars"

Result:

Car {
  Audi,
  Mercedes,
}   
Bus {
}

Regex details:

(?m)       Match the remainder of the regex with the options: ^ and $ match at line breaks (m)
^          Assert position at the beginning of a line (at beginning of the string or after a line break character)
Car        Match the characters “Car” literally
\s         Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *       Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\{         Match the character “{” literally
\s         Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *       Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
}          Match the character “}” literally
  • Related