Search code examples
regexpowershellcontrol-characters

Replace a character with control character Field Seperator(\034) in powershell


(Get-Content C:\Users\georgeji\Desktop\KAI\KAI_Block_2\Temp\KAI_ORDER_DATARECON3.NONPUBLISH) | Foreach-Object {$_ -replace "~", "\034"} | Set-Content C:\Users\georgeji\Desktop\KAI\KAI_Block_2\Temp\KAI_ORDER_DATARECON4.NONPUBLISH

I am using the following command to replace ~ in text file with Field Seperator. This command run sucessfully but when i open the output file in notepadd ++. I am just seeing the plain \034.

Ex:

Company_Identifier\034Primary_Transaction_ID

But the output should be like below

enter image description here

Please Help


Solution

  • Use

    -replace "~", [char]0x1C
    

    If you want to use it inside a longer string, you may use

    -replace "~", "more $([char]0x1C) text"
    

    The point here is that, in Powershell, you cannot use an octal char representation (nor \xYY or \uXXXX) since the escape sequences that it supports is limited to (see source)

       `0  Null
       `a  Alert bell/beep
       `b  Backspace
       `f  Form feed (use with printer output)
       `n  New line
       `r  Carriage return
     `r`n  Carriage return + New line
       `t  Horizontal tab
       `v  Vertical tab (use with printer output)
    

    The `r (carriage return) is ignored in PowerShell (ISE) Integrated Scripting Environment host application console, it does work in a PowerShell console session.

    Using the Escape character to avoid special meaning.

       ``  To avoid using a Grave-accent as the escape character
       `#  To avoid using # to create a comment
       `'  To avoid using ' to delimit a string
       `"  To avoid using " to delimit a string