Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

string replace not working on multiple files

$
0
0

 I have multiple files in c:\test with the *.msg prefix some meet criteria and some don't. If they meet criteria then it does
string replace if not it's supposed to just MOVE file to targetpath. I'm not sure the pattern match is working. One of my files
got replaced but there wasn't 8 positions are the REF\MF* until the tilda(~).  Is there any easy way to debug or can someone
see something wrong in code.

Data examples:

If the record does have  “ST*862”  then look for “REF*MF*”(could be anywhere on that data line)   if the next field  (between the * and ~) is greater than 8 than do replace and move to dest.

ST*862*000066602~ZIP*BE*342215301~REF*MF*9992215301~     


Example of just a move file.

ST*862*000066602~ZIP*BE*342215301~REF*MF*99922101~    

$sourcepath = 'C:\Test\'
$targetpath = 'C:\test\New\'
cd $sourcepath
$oldval = "ST*862*"
$newval = "ST*860*"
$targetfiles = @()
$pattern = "(?<=.*)REF\*MF\*.{9,}~?(?=.*)"
$files = (gci '*.MSG')

foreach ($file in $files) {
    [bool]$flag = $true
    Get-Content -Path $file | % {if ($_ -cmatch $pattern) {
        $flag = $false
        $targetfiles += $file}
    }

    if ($flag) {$file > $(Join-Path $targetpath $file.Name); $flag = $false}
    #Write-Host $file
}
if ($targetfiles.Length -gt 0) {
    foreach ($file in $targetfiles) {
        #Write-Host $file
        get-content -path $file | % { $_ -creplace([Regex]::Escape($oldval), $newval)} | Out-File $(Join-Path $targetpath $file.Name) -Confirm
    }

}

Thanks.

    

Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>