问题
I have a CSV file that contains nearly 4,000+ lines, with random blank lines and comments starting with "#" throughout. I'm trying to import the CSV file while skipping lines that are blank or start with "#". I've tried this:
$csvFile = Import-Csv .\example.csv | Where-Object {$_ -notlike '#*'} | Where-Object {$_ -ne ''}
and this does not work. I've also tried:
$csvFile = Import-Csv .\example.csv
Get-Content $csvFile | Where-Object {$_ -notlike '#*' | Where-Object {$_ -ne ''} | Set-Content newCSV.csv
Both of these result in the file being imported with all lines, and nothing has changed from the original. Is there a better way to do this? I'm stumped.
回答1:
This should do the job:
Get-Content $csvPath | Where-Object { $_ -notmatch '^#|^$' } | Set-Content $strippedCsvPath
^#
matches line starting with #, ^$
matches empty line.
You can simplify testing using following snippet:
$csv = 'line1',
'#line2',
'',
'line4'
$csv | Where-Object { $_ -notmatch '^#|^$' }
If whitespaces are (un)important, if empty lines means lines containing only whitespaces, you can slightly change RegEx to ^\s*#|^\s*$
as follows:
$csv = 'line1',
'#line2',
'',
' ',
' #comment',
'line4'
$csv | Where-Object { $_ -notmatch '^\s*#|^\s*$' }
来源:https://stackoverflow.com/questions/51750456/how-to-delete-lines-in-a-csv-that-start-with-or-are-blank-powershell