问题
Every morning I have a report that generates a CSV file that contains names of computers, as well as additional comments throughout the file. Each line that is a comment starts with "#", and comments are scattered throughout the document, not just at the start of the document so I can't just read over the first couple lines.
Is there any way to search through the CSV file and delete lines that start with "#"? Or is there a way to select lines that don't start with "#", and save them to as a new file?
回答1:
Yes, absolutely.
You could read the file, line by line, and simply filter out anything that starts with #
:
Get-Content $csvPath |Where-Object {$_ -notlike '#*'} |Set-Content $newCsvPath
回答2:
foreach ($thing in $csv) {
if ($thing.StartsWith("#")) {
continue
} else {
#insert what you want to do here
}
}
回答3:
Your duplicate question mentioned that you also want to filter out empty lines. This will do that:
Get-Content "inputfile.csv" |
Where-Object { $_ -notmatch '(^\s*$)|(^\s*#)' } |
Set-Content "outputfile.csv"
来源:https://stackoverflow.com/questions/51710093/how-to-delete-lines-that-start-with-in-a-csv-file