Edit css file using Powershell

Advertisements

theme.css

.actionBlock[selected] {
        color: var(--gray11);
        background-color: var(--gray11);
    }

I want change "color: #FFF"

$file = "theme.css"
$content = Get-Content $file -Raw
$content = $content -replace '(\.actionBlock\[selected\]\s*{[^{}]+color:\s*)([^;]+)(;)', ('$1#FFF; /* EDITED : $2 */')
Set-Content -Path $file -Value $content

Result

.actionBlock[selected] {
        color: var(--gray11);
        background-color: #FFF; /* EDITED : var(--gray11) */
    }

I want change only color not background-color

>Solution :

Your regex is actually almost fine, you just need to make [^{}]+ match lazily by adding ?. See https://regex101.com/r/K6HTYG/1.

$css = @'
.actionBlock[selected] {
  color: var(--gray11);
  background-color: var(--gray11);
}
'@

$css -replace '(\.actionBlock\[selected\]\s*{[^{}]+?color:\s*)([^;]+)(;)', '$1#FFF; /* EDITED : $2 */'

However this would fail fairly easily as soon as color were after background-color, so perhaps a better approach is to look for the line where color is preceded only by white space. See https://regex101.com/r/99QdN3/1.

$css = @'
.actionBlock[selected] {
  background-color: var(--gray11);
  color: var(--gray11);
}
'@

$css -replace '(?m)(?<=\.actionBlock\[selected\]\s*{[^{}]+?^\s*color:\s*)([^;]+);', ' #FFF; /* EDITED :$1 */'

Leave a ReplyCancel reply