Replace multi-line string in all files.

I know my regular expressions replacement works perfectly…

WMI8400123454~" -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

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

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 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*)~",
  set-content $file $content

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!


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)”.