How to delete lines that start with “#” in a CSV file

馋奶兔 提交于 2020-01-14 03:26:27

问题


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

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