Solved Remove CR/LF That Are In Between Double Quotes.

August 20, 2017 at 11:23:25
Specs: Windows 7
This is for Razor, who answered this previously...
Hi Razor,
I'm trying to use your code that you supplied (below)
Could you explain how it works?
Thanks!

Get-Content ".\test.csv" | ForEach-Object {
if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
}


See More: Remove CR/LF That Are In Between Double Quotes.

Reply ↓  Report •

#1
August 20, 2017 at 21:24:49
✔ Best Answer
Get-Content ".\test.csv" | ForEach-Object {
Read "test.csv", one line at a time, stripping off the CR/LF. This is what's actually doing the stripping. The rest of the script is about adding CR/LF's back in at the correct spots.

Get-Content ".\test.csv" | ForEach-Object {
The rest of the code runs for every line of the file.


if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
Add this line to the variable $line, which will either be empty, or all of the lines we've seen since we last felt like adding a line break back in.

if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
Count the number of double quotes $line has so far . . .

if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
. . . Then do a binary AND with 1 (odd number test) . . .

if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
. . . And finally invert the result (even number test).

if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
If all of the double quotes in $line are paired up . . .

if (!([Regex]::Matches(($line += $_), '"').Count -band 1)) { $line; $line = "" }
. . .Dump $line to output. This adds a CR/LF to the end. Then empty out $line so we can start over for the next line.

}
No output specified so results will be dumped to the screen; outputting to a file left as an exercise to the reader.

The thread this came from probably had some level of importance on making sure the double quotes were all paired up, as otherwise this script will eat the end of the output.

How To Ask Questions The Smart Way

message edited by Razor2.3


Reply ↓  Report •
Related Solutions


Ask Question