Replace a text part in textfile: Unterschied zwischen den Versionen

Aus Wiki-WebPerfect
Wechseln zu: Navigation, Suche
Zeile 14: Zeile 14:
  
  
 
+
== PowerShell Skript ==
 
+
 
+
== PowerShell Skript ===
+
 
<source lang="powershell">
 
<source lang="powershell">
 
$FileToChangePath = "C:\Temp\FileToChange.txt"
 
$FileToChangePath = "C:\Temp\FileToChange.txt"
Zeile 27: Zeile 24:
 
$RegexReplace = "(?<=\#\#\#\.Test)(.|\n)*(?=\#\#\#)"
 
$RegexReplace = "(?<=\#\#\#\.Test)(.|\n)*(?=\#\#\#)"
  
If ($ZabbixConf -match $RegexSearch) {
+
If ($FileToChange -match $RegexSearch) {
 
     Write-Host "The text part in the file has been changed." -ForegroundColor Green
 
     Write-Host "The text part in the file has been changed." -ForegroundColor Green
 
     $ChangeTextPart = $FileToChange -replace $RegexReplace, ("`r`n" + $TemplateTextPartPath + "`r`n")
 
     $ChangeTextPart = $FileToChange -replace $RegexReplace, ("`r`n" + $TemplateTextPartPath + "`r`n")

Version vom 27. Juni 2018, 15:33 Uhr

Goal

Replace the text part between ### Test: and ###.

Regex

(?<=<YourStartString>)(.|\n)*(?=<YourEndString>)

Example for a text part:

### Test
This Text will
changed with the following
PowerShell Skript
###

Regex for the example text part below:

(?<=\#\#\#\.Test)(.|\n)*(?=\#\#\#)


PowerShell Skript

$FileToChangePath = "C:\Temp\FileToChange.txt"
$FileToChange = Get-Content $FileToChangePath -Raw
 
$TemplateTextPartPath = Get-Content "C:\Temp\TemplateTextPart.txt" -Raw
 
$RegexSearch = "### Test" #Search the head of text part
$RegexReplace = "(?<=\#\#\#\.Test)(.|\n)*(?=\#\#\#)"
 
If ($FileToChange -match $RegexSearch) {
    Write-Host "The text part in the file has been changed." -ForegroundColor Green
    $ChangeTextPart = $FileToChange -replace $RegexReplace, ("`r`n" + $TemplateTextPartPath + "`r`n")
    Set-Content -Path $FileToChangePath -Value $ChangeTextPart
} Else {
    Write-Host "The text part in the file has been added." -ForegroundColor Yellow
    Add-Content -Path $FileToChangePath -Value ("`r`n" + "`r`n" + "`r`n" + "`r`n" + "### Test" + "`r`n" + $TemplateTextPartPath + "`r`n" + "###" ) -PassThru
}


Regex101: https://regex101.com/