0

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

1
  • You say you want to add a Z, but the example has Xs? Commented May 21, 2014 at 10:58

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

I tried the same syntax in powershell but does not work: $_ -replace 'href=["]X?([^"]*)\.ditamap["]','href="X\1.ditamap"'} | Out-File $mapfolder\$_
0

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\$_
       }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.