如何删除 CSV 中以“#”开头或空白的行 |电源外壳

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

我有一个包含将近 4,000 多行的 CSV 文件,其中有随机的空行和以“#”开头的注释。我正在尝试导入 CSV 文件,同时跳过空白行或以“#”开头的行。我试过这个:

$csvFile = Import-Csv .\example.csv | Where-Object {$_ -notlike '#*'} | Where-Object {$_ -ne ''}

这行不通。我也试过:

$csvFile = Import-Csv .\example.csv
Get-Content $csvFile | Where-Object {$_ -notlike '#*' | Where-Object {$_ -ne ''} | Set-Content newCSV.csv

这两者都会导致文件的所有行都被导入,并且与原始文件没有任何变化。有一个更好的方法吗?我被难住了。

这应该可以完成工作:

Get-Content $csvPath | Where-Object { $_ -notmatch '^#|^$' } | Set-Content $strippedCsvPath

^#匹配以#开头的行,^$匹配空行。

您可以使用以下代码段简化测试:

$csv = 'line1',
'#line2',
'',
'line4'

$csv | Where-Object { $_ -notmatch '^#|^$' }

如果空格(不)重要,如果空行意味着只包含空格的行,您可以将 RegEx 稍微更改为 ^\s*#|^\s*$,如下所示:

$csv = 'line1',
'#line2',
'',
'    ',
'   #comment',
'line4'

$csv | Where-Object { $_ -notmatch '^\s*#|^\s*$' }