我有一个文本文件,其中一个值的中间有一个换行符。在Notepad++中,当显示所有字符时,这就是文件的样子。
Row1-Col1,Row1-Col2,Row1-Col3,Row1-Col4,Row1-Col5
Row2-Col1,Row2-Col2,Row2-Col3,Row2-Col4,Row2-Col5
Row3-Col1,Row3-Col2,Row3-Col3,Row3-
Col4,Row3-Col5
Row4-Col1,Row4-Col2,Row4-Col3,Row4-Col4,Row4-Col5
Row5-Col1,Row5-Col2,Row5-Col3,Row5-Col4,Row5-Col5
使用 Powershell,我需要消除“Row3-”之后的换行以使数据看起来像这样:
Row1-Col1,Row1-Col2,Row1-Col3,Row1-Col4,Row1-Col5
Row2-Col1,Row2-Col2,Row2-Col3,Row2-Col4,Row2-Col5
Row3-Col1,Row3-Col2,Row3-Col3,Row3-Col4,Row3-Col5
Row4-Col1,Row4-Col2,Row4-Col3,Row4-Col4,Row4-Col5
Row5-Col1,Row5-Col2,Row5-Col3,Row5-Col4,Row5-Col5
我已尝试以下操作,但生成的文件与源文件相同。
(Get-Content -Raw $SourceFile).Replace('`nC','C') | Out-File ".\\fixLF.txt" -NoNewline\
请注意,文件中的实际数据比这更复杂。然而,我需要消除的行后面总是有相同的字符。
.Replace
是String
类的实例方法,它对正则表达式一无所知。 PowerShell 中的替换正则表达式运算符是 -replace
。
(?m)\r?\n^(?=C)
:
(Get-Content -Raw $SourceFile) -replace '(?m)\r?\n^(?=C)' | Out-File ".\\fixLF.txt" -NoNewline\
(?<=-)\r?\n
:
(Get-Content -Raw $SourceFile) -replace '(?<=-)\r?\n' | Out-File ".\\fixLF.txt" -NoNewline\