【问题标题】:Replace double quotes in text enclosed with double quotes in CSV file with back slash using PowerShell使用 PowerShell 将 CSV 文件中用双引号括起来的文本中的双引号替换为反斜杠
【发布时间】:2021-06-22 17:10:11
【问题描述】:

我是 PowerShell 新手。 我需要用 CSV 文件中的\" 替换如下文本中的双引号。

输入: "Te"st1","Tes"t2","Test"3"

输出: "Te\"st1","Tes\"t2","Test\"3"

我尝试使用 -replace。但它正在替换 CSV 文件中的所有双引号。只需要在文本内替换引号。

$csv = 'C:\Users\Suresh\Documents\test.txt' (Get-Content $csv) -replace '"','\"' | out-file 'C:\Users\Suresh\Documents\test_out.txt'

【问题讨论】:

  • 所以你想从"的第二个实例开始每隔三分之一替换一次?或者一个值/列是否可以包含多个未转义的"
  • @MathiasR.Jessen,一列可以包含多个未转义的`"。
  • 我认为您的输入无法被明确解析。
  • 不擅长regex,但试试这样的东西,可能对你有用:'"Te"st1","Tes"t2","Test"3","Test4"",""Test5"' -replace '([\w"])"([\w"])','$1\"$2'
  • 在 csv 中,当字段包含引号时,该引号应加倍,而不是以反斜杠为前缀。

标签: powershell


【解决方案1】:

试试

 -replace '(?<=\w)\"(?=\w)','\"'

例子

$tempfile = New-TemporaryFile

@'
"Column1","Column2","Column3"
"Te"st1","Tes"t2","Test"3"
'@ | Set-Content $tempfile

(Get-Content $tempfile) -replace '(?<=\w)\"(?=\w)','\"' | Set-Content $tempfile

Get-Content $tempfile

输出

"Column1","Column2","Column3"
"Te\"st1","Tes\"t2","Test\"3"

正则表达式模式使用向前看和向后看,只对两边都有单词字符的双引号起作用。您可以调整以接受不只是相邻的单词字符。你也可以反其道而行之,例如只处理那些前后没有逗号的。

【讨论】:

  • 不错的一个,如果你有这两个你会怎么做? "Test4"",""Test5"。应该是这样吗? '(?&lt;=[\w"])\"(?=[\w"])','\"'
  • 那不是一个有效的 CSV 文件。
  • 对于这个复杂的需求,这可能是可行的。 -replace '(?
  • 是的,我在 regex101 上查看它。谢谢!
  • Regex 非常灵活和强大。不过,您已经知道了,因为您正在尝试了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2018-02-13
  • 2019-11-29
  • 2022-01-27
  • 2023-02-24
  • 1970-01-01
  • 2015-08-29
相关资源
最近更新 更多