Quickest way to organize categorized data in a text file and convert to CSV

前端 未结 5 1107
粉色の甜心
粉色の甜心 2021-01-24 03:25

I have a text file with hundreds of rows. Data fields and values separated by a colon and one empty line separating each data set. It looks something like this...

ico         


        
5条回答
  •  無奈伤痛
    2021-01-24 04:20

    A way to do what you want in simple, and hopefully clear code. I did not use sophisticated PS objects, methods or functions so it that it is clear and simple. The input is expected to be in a text file called in1.txt. I assume that each set of date has at most 7 lines (before a space or end-of-file is encountered). I did not make it generic or include error checking, etc. Needless to say, there are many other ways you can do this. If you have any comments let me know.

    #======================
    # Function used by code
    #======================
    
    Function func-PrintSet
    {
    
     $s1=''
     $del= ','
     $q='"'
     foreach ($element in $arr1) {
         $s1=$s1+$q+$element+$q + $del 
     }
     $s1
    
     $s1=""
     foreach ($element in $arr2) {
         $s1=$s1+$q+$element+$q +  $del 
     }
     $s1
    
    }
    
    #=====================
    # Main code
    #=====================
    
    # simple initialization of arrays.
    
    $arr1=0,0,0,0,0,0,0
    $arr2=0,0,0,0,0,0,0
    $i=-1
    $reader = [System.IO.File]::OpenText("in1.txt")
    while ($null -ne ($line = $reader.ReadLine())) 
    {
        IF ($line)
        {
    
             $items = $line.split(':')
             $i=$i+1
             $arr1[$i]= $items[0]
             $arr2[$i]= $items[1]
        }
        ELSE
        {
    
            func-PrintSet   
            $i=-1
        }
    }
    func-PrintSet
    
    "Done :)"
    
    # Code end
    

提交回复
热议问题