【问题标题】:Replace a character with control character Field Seperator(\034) in powershell在powershell中用控制字符字段分隔符(\ 034)替换一个字符
【发布时间】:2017-10-14 13:44:27
【问题描述】:
(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

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

例如:

Company_Identifier\034Primary_Transaction_ID

但输出应该如下所示

请帮忙

【问题讨论】:

  • 试试-replace "~", [char]0x1C
  • 太棒了……成功了……
  • 我是 powershell 新手。请提供一些链接,我可以更好地了解 powershell 中的控制字符。在 unix 中我们使用 \034 但它在 powershell 中不起作用

标签: regex powershell control-characters


【解决方案1】:

使用

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

`r(回车)在 PowerShell (ISE) 集成脚本环境宿主应用程序控制台中被忽略,它在 PowerShell 控制台会话中工作。

使用转义字符来避免特殊含义。

   ``  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

【讨论】:

    【解决方案2】:

    Windows PowerShell 目前(见下文)没有字符文字的转义序列,例如\034

    相反,您可以在子表达式中将数字 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}"} |...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2016-11-06
      • 2013-12-08
      • 1970-01-01
      • 2014-08-28
      相关资源
      最近更新 更多