Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Find/Replace pattern of ASCII control characters

I'm trying to write a script to search the contents of a file, and when it comes across a grouping of ASCII control characters, to insert a CR/LF.

The pattern of characters I would like to replace are [ETX][NUL][STX][ETX][SOH]

    $filenames = @(Get-Childitem "E:\VendorFiles\*")

    $CR = @("[char]3 [char]0 [char]2 [char]3 [char]1")
    foreach ($file in $filenames) {$outfile = "$file" + ".txt"
    Get-Content $file | Foreach-object {
            $_ -replace $CR,"`r`n" `
             -replace [char]3,"|" `
             -replace [char]1,"{" `
             -replace "\\","\\" `
        } | Set-Content -encoding "UTF8" $outfile}
like image 271
Jerry Sweeton Avatar asked Mar 11 '13 16:03

Jerry Sweeton


1 Answers

This expression:

@("[char]3 [char]0 [char]2 [char]3 [char]1")

...creates an array with a single element. You need commas between terms if you really want an array of 5 items, but -replace does not support arrays anyway. Also, your single element contains the literal characters you typed; not what you expected.

What you need is to create a simple string to feed to -replace; this is a bit more involved when you are dealing with non-printable characters. You had the right idea--you just have to tell PowerShell to interpolate the code expressions within your string using the $() notation on each expression:

$CR = "$([char]3)$([char]0)$([char]2)$([char]3)$([char]1)"
like image 146
Michael Sorens Avatar answered Sep 21 '22 01:09

Michael Sorens