locked
deleting lines and columns in file using powershell RRS feed

  • Question

  • hello everyone,

    hope it is the right forum catagory.

    i am totally new to powershell (no experience at all) but i was told that powershell could solve my problem:

    i have around three hundred .dat files with eight lines and 2044 columns.  I just need lines number 2 and 4, the rest can be deleted! 

    And colums 1800 to end can be deleted. 

    Thanks in advance 

    here is a link to a .dat file
    https://tinyurl.com/yarnol6x 


    • Edited by daroox Monday, September 25, 2017 4:57 PM
    Monday, September 25, 2017 4:51 PM

All replies

  • I'm not sure how you want the data points delimited, but this script can be modified to achieve the desired result.

    This script loads the file, and selects rows 2 and 4 (index 1 and 3). Then, in a foreach loop, the data points are split by tabs, and the first 1800 are appended to a string. This string is then added to a data array. Finally, the data array is written to a new file (new100.dat).

    $filePath = 'PATHTOFILE\100.dat'
    
    $data = get-content -Path $filePath
    $newData = @();
    
    foreach($row in $data | Select-Object -Index 1,3)
    {
        $cols = $row.split('	')
    
        $rowString = ""
    
        for($i=0; $i -lt 1800; $i++)
        {
            $rowString += $cols[$i]
    
            if($i % 1799 -ne 0)
            {
                $rowString += '	'
            }
        }
        $newData += $rowString
    }
    
    $newData | Out-File 'PATHTONEWFILE\new100.dat'

    • Proposed as answer by Robotitude Monday, October 12, 2020 2:27 PM
    Saturday, October 3, 2020 1:44 AM
  • For powershell,only 1 great link is needed,follow the Microsoft/TechNet below.

    https://gallery.technet.microsoft.com/scriptcenter

    However this link is getting retired.

    Saturday, October 3, 2020 5:53 AM