Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting columns from text file using PowerShell

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...

like image 368
atricapilla Avatar asked Mar 23 '10 19:03

atricapilla


People also ask

How do I extract data from a text file in PowerShell?

One of the easiest tasks is retrieving all text from an existing text file. For most text files, a PowerShell scripter can use the Get-Content cmdlet. The Get-Content cmdlet is a very popular PowerShell cmdlet that will retrieve all text from a text file specified by the Path parameter.

What is parsing in PowerShell?

As PowerShell parses command input it tries to resolve the command names to cmdlets or native executables. If a command name does not have an exact match, PowerShell prepends Get- to the command as a default verb. For example, PowerShell parses Service as Get-Service .

How do I read a text file in PowerShell?

When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.


1 Answers

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. :-)

like image 128
Keith Hill Avatar answered Sep 19 '22 03:09

Keith Hill