How to delete lines in a CSV that start with “#” or are blank | PowerShell

≡放荡痞女 提交于 2019-12-11 18:51:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!