Extracting columns from text file using PowerShell

▼魔方 西西 提交于 2019-12-09 14:54:32

问题


I have to extract columns from a text file explained in this post:

Extracting columns from text file using Perl one-liner: similar to Unix cut

but I have to do this also in a Windows Server 2008 which does not have Perl installed. How could I do this using PowerShell? Any ideas or resources? I'm PowerShell noob...


回答1:


Try this:

Get-Content test.txt | Foreach {($_ -split '\s+',4)[0..2]}

And if you want the data in those columns printed on the same line:

Get-Content test.txt | Foreach {"$(($_ -split '\s+',4)[0..2])"}

Note that this requires PowerShell 2.0 for the -split operator. Also, the ,4 tells the the split operator the maximum number of split strings you want but keep in mind the last string will always contain all extras concat'd.

For fixed width columns, here's one approach for column width equal to 7 ($w=7):

$res = Get-Content test.txt | Foreach {
           $i=0;$w=7;$c=0; `
           while($i+$w -lt $_.length -and $c++ -lt 2) {
               $_.Substring($i,$w);$i=$i+$w-1}}

$res will contain each column for all rows. To set the max columns change $c++ -lt 2 from 2 to something else. There is probably a more elegant solution but don't have time right now to ponder it. :-)




回答2:


Assuming it's white space delimited this code should do.

$fileName = "someFilePath.txt"
$columnToGet = 2
$columns = gc $fileName | 
   %{ $_.Split(" ",[StringSplitOptions]"RemoveEmptyEntries")[$columnToGet] }



回答3:


To ordinary、

type foo.bar | % { $_.Split(" ") | select -first 3 }



回答4:


Try this. This will help to skip initial rows if you want, extract/iterate through columns, edit the column data and rebuild the record:

$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")     

Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {

    $record = $indexName 
    foreach ($property in $_.PSObject.Properties){

        #doSomething $property.Name, $property.Value

            if($property.Name -like '*CUSIP*'){

                $record = $record + "," + '"' + $property.Value + '"' 
            }
            else{
                $record = $record + "," + $property.Value 
            }                           
    }               

        $array.add($record) | out-null  
        #write-host $record                         
}


来源:https://stackoverflow.com/questions/2503010/extracting-columns-from-text-file-using-powershell

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