【发布时间】:2021-05-03 04:08:10
【问题描述】:
我正在处理一个大型 csv 文件,其中包含用双引号括起来的字段,其中包含包含非转义双引号的文本描述,我需要用转义双引号替换它。我尝试使用以下正则表达式:(?<!^|",)("(?:$[^"])|"(?!,"|$)),它能够找到未转义的引号,除非它们后跟换行符。非常感谢您解决此问题的任何帮助。
我知道 csv 格式不正确,但遗憾的是无法控制,因此我需要能够更正格式以进行进一步处理。
例子:
"Field 1","Field 2","Field 3 "with unescaped quote"
followed by line break","Field 4"
需要成为:
"Field 1","Field 2","Field 3 ""with unescaped quote""
followed by line break","Field 4"
我使用的Powershell脚本如下:
[string]$path = 'C:\ ...'
[string]$directory = [System.IO.Path]::GetDirectoryName($Path);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($Path);
[string]$extension = [System.IO.Path]::GetExtension($Path);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
$reader = New-Object 'System.IO.StreamReader'($path, $true);
$regex = [regex] '(?<!^|",)("(?:$[^"])|"(?!,"|$))'
$writer = [System.IO.StreamWriter] $newFilePath;
try{
while (($line = $reader.ReadLine()) -ne $null ){
$newline = $line -replace $regex, '""';
$writer.WriteLine($newline);
}
}
finally{
$reader.Close();
$writer.Close();
}
【问题讨论】:
-
你如何阅读你的文件?你在用
Get-Content吗?见:Search multiline text in a file using powershell -
此外,我认为您需要重新定义您的定义,因为
...break","Field 4"还包含一个“未转义的双引号后跟换行符”。这意味着您可能必须通过计算字段来解决此问题,或者查找 不以双引号开头的行。
标签: regex powershell csv