How to replace '= ' with '=none'

89 views Asked by At

i have this noempty.txt

Caption=http://support.microsoft.com/?kbid=3150513

CSName=DC04

Description=Update

FixComments=

HotFixID=KB3150513

InstallDate=

InstalledBy=NT AUTHORITY\SYSTEM

InstalledOn=11/29/2022

Name=

ServicePackInEffect=

Status=

for example the line "FixComments=" or "InstallDate=" or "name=" i have to add in every line the word "none"

I try whit

(Get-Content -Path c:\path\noempty.txt) | ForEach-Object {$_ -Replace '=\s', '=NONE'} | Set-Content -Path c:\path\noempty2.txt

But it doesn't work

Any advice? Thank you very much Alex

(Get-Content -Path c:\path\noempty.txt) | ForEach-Object {$_ -Replace '=\s', '=NONE'} | Set-Content -Path c:\path\noempty2.txt

for example the line "FixComments=" or "InstallDate=" or "name=" i have to add in every line the word "none"

1

There are 1 answers

0
The fourth bird On

You could read the whole file, match the parts that you are interested in and using the full match with $0 followed by NONE in the replacement.

$pattern = "(?m)^[^\s=]+=[\p{Zs}\t]*$"
(Get-Content c:\path\noempty.txt -Raw) -replace $pattern, '$0NONE'

The pattern matches:

  • (?m) Inline modifier to enable multiline
  • ^ Start of string
  • [^\s=]+ Match 1+ times a non whitespace character except for =
  • = Match literally
  • [\p{Zs}\t]* Match optional horizontal whitespace characters
  • $ End of string

See the regex matches.

Output

Caption=http://support.microsoft.com/?kbid=3150513

CSName=DC04

Description=Update

FixComments=NONE

HotFixID=KB3150513

InstallDate=NONE

InstalledBy=NT AUTHORITY\SYSTEM

InstalledOn=11/29/2022

Name=NONE

ServicePackInEffect=NONE

Status=NONE

If you don't want to keep possible trailing spaces after the equals sign, you can use a capture group, and that group 1 in the replacement instead of the whole match:

$pattern = "(?m)^([^\s=]+=)[\p{Zs}\t]*$"
(Get-Content c:\path\noempty.txt -Raw) -replace $pattern, '$1NONE'

See the group 1 matches.