简体   繁体   中英

RegEx required for search-replace using PowerShell

I'm trying to load up a file from a PS script and need to search replace on the basis of given pattern and new values. I need to know what the pattern would be. Here is an excerpt from the file:

USER_IDEN;SYSTEM1;USERNAME1;
30;WINDOWS;Wanner.Siegfried;
63;WINDOWS;Ott.Rudolf;
68;WINDOWS;Waldera.Alicja;
94;WINDOWS;Lanzl.Dieter;
98;WINDOWS;Hofmeier.Erhard;

ReplacerValue: "@dummy.domain.com" What to be replaced: USERNAME1 column

Expected result:

USER_IDEN;SYSTEM1;USERNAME1;
30;WINDOWS;Wanner.Siegfried@dummy.domain.com;
63;WINDOWS;Ott.Rudolf@dummy.domain.com;
68;WINDOWS;Waldera.Alicja@dummy.domain.com;
94;WINDOWS;Lanzl.Dieter@dummy.domain.com;
98;WINDOWS;Hofmeier.Erhard@dummy.domain.com;

Also, the file can be like this as well:

USER_IDEN;SYSTEM1;USERNAME1;SYSTEM2;USERNAME2;SYSTEM3;USERNAME3;
30;WINDOWS;Wanner.Siegfried;WINDOWS2;Wanner.Siegfried;LINUX;Dev-1;LINUX2;QA1
63;WINDOWS;Ott.Rudolf;WINDOWS2;Ott.Rudolf;LINUX;Dev-2
68;WINDOWS;Waldera.Alicja;
94;WINDOWS;Lanzl.Dieter;WINDOWS4;Lanzl.Dieter;WINDOWS3;Lead1
98;WINDOWS;Hofmeier.Erhard;

In the above examples, I want to seek the values under USERNAME n columns but there is a possibility that the column row may not be present but the CSV (;) and the pairs will remain same and also the first value is the identifier so it's always there.

I have found the way to start but need to get the pattern:

(Get-Content C:\script\test.txt) | 
Foreach-Object {$_ -replace "^([0-9]+;WINDOWS;[^;]+);$", '$@dummy.domain.com;'} | 
Set-Content C:\script\test.txt

Edit I came up with this pattern: ^([0-9]+;WINDOWS;[^;]+);$ It is very much fixed to this particular file only with no more than one Domain-Username pair and doesn't depend on the columns.

I think that using a regex to do this is going about it the hard way. Instead of using Get-Content use Import-Csv which will split your columns for you. You can then use Get-Memeber to identify the USERNAME columns. Something like this:

$x = Import-Csv YourFile.csv -Delimiter ';'
$f = @($x[0] | Get-Member -MemberType NoteProperty | Select name -ExpandProperty name | ? {$_ -match 'USERNAME'})
$f | % {
  $n = $_
  $x | % {$_."$n" = $_."$n" + '@dummy.domain.com'}
} 
$x | Export-Csv .\YourFile.csv -Delimiter ';' -NoTypeInformation

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