PowerShell - open a file, find a string in a line and replace a string in a previous line -


there sample data file

session 1: {21ad8b68-2a42-459e-bd29-f082f47e71b2}   started: 06-24-2015 11:00   nds tree: test_tree   ad server: dc01.adatum.com   o=branch/ou=branch_city1/cn=user1   user   cn=user1,ou=branch_city1,ou=adatum,dc=adatum,dc=com   user   o=branch/ou=branch_city1/cn=everyone1   group   cn=everyone1,ou=branch_city1,ou=adatum,dc=adatum,dc=com   group   o=branch/ou=branch_city2/cn=user2   user   cn=user2,ou=branch_city2,ou=adatum,dc=adatum,dc=com   user   o=branch/ou=branch_city2/cn=everyone2   group   cn=everyone2,ou=branch_city2,ou=adatum,dc=adatum,dc=com   group  

i find line contains string "group" (case sensitive) or "user" (case sensitive). if there match, line before should changed this:

if "user" change line before cn=<...>,ou=adatum,dc=adatum,dc=com
if "group" change line before cn=<...>,ou=groups,ou=adatum,dc=adatum,dc=com

of course, output data file contains changes.

any idea?

many in advance,
m.

the easiest way accomplish using regular for loop keep track of line numbers - if line $n matches "user", replace string in line $n-1.

to case-sensitive regex, use -cmatch (notice c prefix). in example below i've used named capture group ((?<name>pattern)) match , capture either user or group.

the last part, adding new path existing cn=<...> part can accomplished -split command , lookbehind avoid messing escaped commas in cn value:

# read file, line line $samplefile = @(get-content c:\path\to\data.txt) # loop on text line numbers for($i=0;$i -lt $samplefile.count;$i++){     # test if line matches     if(![string]::isnullorwhitespace($samplefile[$i]) -and $samplefile[$i].trim() -cmatch "(?<type>^group|user$)"){         # if so, use match determine dn suffix         switch($matches["type"]){             "group" { $samplefile[$i-1] = "{0},ou=groups,ou=adatum,dc=adatum,dc=com" -f ($samplefile[$i-1] -split "(?<!\\),")[0] }             "user"  { $samplefile[$i-1] = "{0},ou=adatum,dc=adatum,dc=com" -f ($samplefile[$i-1] -split "(?<!\\),")[0] }         }     } } $samplefile | out-file c:\path\to\output.txt -force  

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -