Author Posts

August 1, 2018 at 4:37 pm

I know my regular expressions replacement works perfectly...

"SBR*S*18*999999******MC~
NM1*IL*1*BRxxxELL*CAxxxR*W***MI*8400123454~" -replace "(?ms)(SBR\*\w\*\d{2}\*)(\w*)(\*\*\*\*\*\*\w*~\s*)(\nNM1\*\S*\*)(\S*)~",'$1$5$3$4$5~' 

But I can't seem to get it to loop through my files to make the replacement. The file below has the exact string as above.

$configFiles = Get-ChildItem -path "C:\test2\QTR2WHCfull\QTR2WHC\test\" 81XP041918WIMedicaidHosp1_837_5.DAT
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_   -replace "(?ms)(SBR\*\w\*\d{2}\*)(\w*)(\*\*\*\*\*\*\w*~\s*)(\nNM1\*\S*\*)(\S*)~",'$1$5$3$4$5~'
  
    } |    set-Content $file.PSPath
}

August 1, 2018 at 5:11 pm

Maybe I am missing something – but why do you need to do it by line? Couldn't you just do the whole file?

foreach($file in $configFIles)
{
     (Get-Content -Path $file.PSPath) -replace "(?ms)(SBR\*\w\*\d{2}\*)(\w*)(\*\*\*\*\*\*\w*~\s*)(\nNM1\*\S*\*)(\S*)~",'$1$5$3$4$5~' | Set-Content -Path $file.PSPath
}

August 1, 2018 at 6:55 pm

How come you started a new thread? Like I said in the other one, you can use "get-content -raw" for multi-line regex search and replace. And use ".*?" instead of "\n" for the line break. A windows text file will have "\r\n" between lines. There may be other problems with your regex. I recommend using http://regex101.com. The last example I gave in the other thread works.

foreach ($file in $files) {
  $content = get-content -raw $file
  # regex may have problems
  $content = $content -replace "(?ms)(SBR\*\w\*\d{2}\*)(\w*)(\*\*\*\*\*\*\w*~\s*)(.*?NM1\*\S*\*)(\S*)~",
    '$1$5$3$4$5~'
  set-content $file $content
}

August 2, 2018 at 10:54 am

JS,
I didn't really understand your post from the previous thread but your solution above worked. How did you know I needed to use the Unix syntax. I spent several days trying to get this to work. Much thanks for your help!

-Kevin

August 2, 2018 at 2:39 pm

I didn't know you were on unix. But windows text files end lines with '\r\n' and unix text files end lines with '\n'. (Osx text files end lines with '\r'.) Ironically, multi-line strings in windows powershell only have '\n'. None of this is usually visible. The bottom status bar in the emacs editor will give a sign of the text file type, "(Unix)", "\", or "U(Mac)".