1

I have a CSV file which has the following for example:

data1,data2,data3,data4,data5
,,,,,
data6,data7,data8,data9,data0

New lines are CRLF (`r`n) as viewed in Notepad++.

I have this in my PowerShell script to remove the line with all commas:

(Get-Content $csvPath) | Foreach-Object {$_ -replace ",,,,,`r`n", ""} | Set-Content $csvPath2

The script will not detect the returns. Even if I remove the commas and just have `r`n. However, I can replace the commas with `r`n without issues.

How can I remove that entire line of commas so that it appears as below?

data1,data2,data3,data4,data5
data6,data7,data8,data9,data0

1 Answer 1

3

Use:

$lines = get-content C:\temp\test.txt | ?{$_ -notlike ",,,,*"}
$lines.count

Here the file test.txt contains:

data1,data2,data3,data4,data5
,,,,
data6,data7,data8,data9,data0

The output is:

data1,data2,data3,data4,data5
data6,data7,data8,data9,data0
Sign up to request clarification or add additional context in comments.

2 Comments

Knows Not Much is correct. The reason why your original attempt wasn't working is that by default, Get-Content returns an array of strings, with the delimiter being a line break. So when you pipe it to ForEach-Object, none of the individual lines will have a line break in it. Alternately, if you really want to use the -replace method, add the -Raw parameter to the Get-Content cmdlet (or use -ReadCount 0 if you're on PowerShell 2 or lower).
Thank you both very much. The solution from Knows Not Much worked. And @KevinD thank you for the explanation. It makes sense as to why it was not working. I appreciate your assistance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.