Link to home
Start Free TrialLog in
Avatar of jskfan
jskfanFlag for Cyprus

asked on

Find and Replace string using Powershell

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

Avatar of footech
footech
Flag of United States of America image

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

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Avatar of jskfan

ASKER

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
Avatar of jskfan

ASKER

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.
Avatar of jskfan

ASKER

Thank you Guys!!