Powershell: Remove Blank lines, line feed and carriage return from a file

Posted: November 4, 2015 in PowerShell

# read the csv in binary
$TGT_DIR=”H:\Desktop”
$repair = get-content -encoding byte $TGT_DIR\FNFG_CUSTOMER.csv

$fixed = New-Object System.Collections.ArrayList
$byteEncoder = New-Object System.Text.ASCIIEncoding
$in_quotes = 0
foreach ($c in $repair) {
# toggle in-quotes flag
if ($c -eq 34) {
$in_quotes = !$in_quotes;
}
# skip carriage returns in quotes
if ($c -eq 13 -and $in_quotes) {
continue;
}
# replace line feeds in quotes with <br>’s
if ($c -eq 10 -and $in_quotes) {
foreach ($b in $byteEncoder.GetBytes(“”)) {
[void]$fixed.Add($b);
}
continue;
}
# pass-through bytes
[void]$fixed.Add($c);
}

# writeout fixed csv
set-content -encoding byte -path $TGT_DIR\FNFG_CUSTOMER.csv -value $fixed

# carry on
$sfactivity = Import-Csv $TGT_DIR\FNFG_CUSTOMER.csv
(get-content $TGT_DIR\FNFG_CUSTOMER.csv) | where {$_ -ne “”} | where {$_ -ne “,”} | out-file $TGT_DIR\FNFG_CUSTOMER.csv

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s