如何删除CSV中以“#"开头的行或为空|电源外壳 [英] How to delete lines in a CSV that start with "#" or are blank | PowerShell
问题描述
我有一个CSV文件,其中包含将近4,000多个行,其中的随机空白行和注释始终以#"开头.我正在尝试导入CSV文件,同时跳过空白行或以#"开头的行.我已经尝试过了:
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.
推荐答案
这应该可以完成:
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 '^#|^$' }
如果空格(不重要),如果空行表示仅包含空格的行,则可以将RegEx略微更改为^\s*#|^\s*$
,如下所示:
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*$' }
这篇关于如何删除CSV中以“#"开头的行或为空|电源外壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!