We help IT Professionals succeed at work.

Find and Replace string using Powershell

jskfan
jskfan used Ask the Experts™
on
Find and Replace string using Powershell

I have  a file Test.txt on a remote computer  named Windows7

the Test.txt  has a line:
aaaa bbbbb   -username  username

Open in new window


I would like to replace the second username with a string 'white'. the command line below works fine, however it is replacing both -username and username with 'white', I need just the second one replaced.
Thank you

((Get-Content -path '\\windows7\c$\test.txt' -Raw) -replace 'username','white') | Set-Content -Path '\\windows7\C$\test.txt'

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

Commented:
You can use this modification.
-replace '(?<=-username +)username','white'

Open in new window

Top Expert 2014
Commented:
I think this is a simpler pattern to do your replacement:
-replace ' username', ' white'

Open in new window

Top Expert 2014

Commented:
True, it is simpler.

To expound a bit for the OP -  It is also less specific in what it will match, which is not necessarily a bad thing -  just depends on the file contents whether the specificity is needed or not.  I tend to err on the side of being more specific with regex patterns.  If you're not certain whether your search string could appear in other places in the file, you should decide whether you want those other instances changed as well - if not then more specificity is better; if not then less specificity is better..  The regex pattern can also be defined to help with things like removing extra spaces if that was desired.

Author

Commented:
I used this:
-replace ' username', ' white'

there are 2 spaces between -username  username

how do I change the command to include 2 spaces... for now it does the change but it shows -usernamewhite

Author

Commented:
I guess i figured it out , just add another space before white

 -replace ' username' , ' white'
I guess i figured it out , just add another space before white

You use the regular expression for either 1 or more, or 1 to 2, or 2 spaces. E.g.

1 or more spaces
-replace " +username", "white"

Open in new window


Or

1 to 2 spaces
-replace " {1,2}username", "white"

Open in new window


Or

Exactly 2 spaces
-replace " {2}username", "white"

Open in new window


A double space in regex is particularly unreadable.

Author

Commented:
Thank you Guys!!