user1749707
user1749707

Reputation: 157

Powershell RegEx to replace text in multiple files

I am very new to powershell and Regular Expression. I would like to use powershell and regular expression to update as follows:

i have text in following pattern.

<Music href="6000111.genre" title="AAA">
  <Music format="ditamap" href="000760.rock" title="222"/>
  <Music format="ditamap" href="Z000756.rock" title="333"/>
</Music>

I need to add previx 'Z' infront of href with extension .rock (if Z does not exist already). that is href="000760.rock --> href="Z000760.rock

<Music href="6000111.genre" title="AAA">
   <Music format="ditamap" href="X000760.rock" title="222"/>
   <Music format="ditamap" href="X000756.rock" title="333"/>
</Music>

I should be getting the following as result:

Will really appreciate your help. regards, rnv

Upvotes: 0

Views: 1901

Answers (3)

user1749707
user1749707

Reputation: 157

Thanks mjolinor,

here is how i integrated your answer:

function replaceText{
    get-childitem -path $mapfolder | 
     Where-Object {$_.extension -eq ".mus"} | 
       foreach-object {
         echo " Replace dita map maprev: $_"
  (Get-Content $mapfolder\$_) | 
     Foreach-Object {
    $_ -replace '(.+href=")[a-z]?(\d+\.rock".+)','$1X$2'} |
                Out-File $mapfolder\$_
       }
}

Upvotes: 0

mjolinor
mjolinor

Reputation: 68341

I'm still not clear about exactly what's in your input file (in terms of existing prefixes) and exactly you want to handle those.

Here's my best guess at a sample solution:

@'
<Music href="6000111.genre" title="AAA">
  <Music format="ditamap" href="000760.rock" title="222"/>
  <Music format="ditamap" href="Z000756.rock" title="333"/>
</Music>
'@ | set-content testfile.txt

filter Set-XRock { $_ -replace '(.+href=")[a-z]?(\d+\.rock".+)','$1X$2' }

get-content testfile.txt | Set-XRock | Set-Content newfile.txt

get-content newfile.txt

<Music href="6000111.genre" title="AAA">
  <Music format="ditamap" href="X000760.rock" title="222"/>
  <Music format="ditamap" href="X000756.rock" title="333"/>
</Music>

You can also use lookaround regexes, but for replacing/inserting into the middle of a string I usually find it makes for more intuitive code to capture the text fore and aft of the replace/insert point and use backreferences to rebuild the string with the replaced/inserted text in between.

Upvotes: 2

user1749707
user1749707

Reputation: 157

In UltraEdit i am doing the following as RegEx (Perl)

find: href=["]X?([^"]*).ditamap["] replace: href="X\1.ditamap"

Upvotes: 0

Related Questions