简体   繁体   中英

Powershell replace exact string

I want to replace a simple string "WEEK." (with a dot) in a text file with the string "TEST"

$LOG= "C:\FILE.TXT"
$A= "TEST"
(Get-Content $LOG) | Foreach { $_ -Replace "WEEK.", $A } | Set-Content $LOG;

The problem is that my file has this content:

WEEK_A WEEK.

And when I run my script the result is:

TESTA TEST

and the result that i want is:

WEEK_A TEST

I try with ^ "WEEK." and "^WEEK.$" but it not worked

Can you help me with the regexp? Thanks

====== EDIT ==================

Ok. I try with

$LOG= "C:\FILE.TXT"
$A= "TEST"
(Get-Content $LOG) | Foreach { $_ -Replace "WEEK\.", $A } | Set-Content $LOG;

and seems its works

The reason why this happened is because you have used pattern WEEK. The dot was a problem: in a regular expression world, the dot means "any character". That's why it was replacing both WEEK_ and WEEK. .

When you have added backslash, then the dot was escaped ie. it lost it's special meaning. Thus making it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM