用powershell中的控制字符Field Seperator(\034)替换一个字符

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 "~", "4"} | Set-Content C:\Users\georgeji\Desktop\KAI\KAI_Block_2\Temp\KAI_ORDER_DATARECON4.NONPUBLISH

我正在使用以下命令将文本文件中的 ~ 替换为字段分隔符。 此命令 运行 成功但是当我在记事本 ++ 中打开输出文件时。我只看到普通的 \034.

例如:

Company_Identifier4Primary_Transaction_ID

但输出应该如下所示

请帮忙

使用

-replace "~", [char]0x1C

如果你想在一个较长的字符串中使用它,你可以使用

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

这里的要点是,在 Powershell 中,您不能使用八进制字符表示(也不能使用 \xYY\uXXXX),因为它支持的转义序列仅限于(参见 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

Windows PowerShell 当前(见下文)没有字符文字的转义序列,如 4

相反,您可以将数字 ascii 或 unicode 值转换为子表达式中的 [char]

"Company_Identifier$([char]0x1C)Primary_Transaction_ID"

同样,您可以提供与-replace最右侧操作数相同的转换表达式,它将被转换为单字符字符串:

... |Foreach-Object {$_ -replace "~", [char]0x1C} |...

PowerShell 6.0(目前处于测试阶段)为 unicode 代码点文字引入了 `u{} 转义序列:

... |Foreach-Object {$_ -replace "~", "`u{1C}"} |...