YoavKlein
YoavKlein

Reputation: 2705

Powershell sed-like opertaion

Consider the following use case: I have a file in this format:

some_content
major_version=1
minor_version=33
some_other_content
combined_version=1.33
more_content

I want to write a Powershell script that takes Major/Minor as parameter, and increments the corresponding number in the file. So I tried using the -replace operator. This is what I came up with:

# Let's say $Major and $Minor contains the updated numbers (I mean, I incremented one of them by 1, according to the user selection)

$SearchExpr = '(?s)(?<First>.*major\D+)\d+(?<Second>.*minor\D+)\d+(?<Third>.*combined\D+)\d+\.\d+'
$ReplaceExp = "`${First}${Major}`${Second}${Minor}`${Third}${Major}.${Minor}"

$VersionFileContent -replace $SearchExp, $ReplaceExp | Out-File $VersionFile

But it's pretty nasty. The probelm is, that while replacing a string in a text is easy if you know the text, like:

"Girrafe, Zebra, Dog" -replace 'Dog', 'Cat'

Replacing "Whatever is after 'Zebra' " is less..

Ideas?

Upvotes: 0

Views: 188

Answers (1)

Theo
Theo

Reputation: 61188

You could use switch -Regex -File for this quite easily:

$content = switch -Regex -File 'D:\Test\MyFile.txt' {
    '^(major|minor)_version=(\d+)' {
        '{0}_version={1}' -f $matches[1], ([int]$matches[2] + 1)
    }
    default { $_ }
}
# for safety, save to a new file
$content | Set-Content -Path 'D:\Test\MyUpdatedFile.txt' -Force

Result:

some_content
major_version=2
minor_version=34
some_other_content
combined_version=1.33
more_content

If you also need to update the combined_version, extend to:

$content = switch -Regex -File 'D:\Test\MyFile.txt' {
    '^(major_version)=(\d+)' {
        $major = [int]$matches[2] + 1
        '{0}={1}' -f $matches[1], $major
    }
    '^(minor_version)=(\d+)' {
        $minor = [int]$matches[2] + 1
        '{0}={1}' -f $matches[1], $minor
    }        
    '^(combined_version)=(\d+)' {
        '{0}={1}.{2}' -f $matches[1], $major, $minor
    }  
    default { $_ }
}

$content | Set-Content -Path 'D:\Test\MyUpdatedFile.txt' -Force

Upvotes: 1

Related Questions