PowerShell: How to Extract Specific Columns from Text File


Often you may want to use PowerShell to extract specific columns from a text file.

You can use the following syntax to do so:

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

This particular example will extract the columns in index positions 0 and 3 from the file named players.txt.

Here is what the various commands do:

  • Get-Content: Returns all lines from the file
  • Foreach: Specifies an action to perform on each row of the file
  • $_ -split ‘\s+’: Split the values in the current row using one or more spaces as the delimiter
  • [0,3]: Only return the values from index positions 0 and 3 after the split

The following example shows how to use this syntax in practice.

Example: How to Extract Specific Columns from Text File in PowerShell

Suppose we have a text file in our current directory named players.txt that contains information about various basketball players.

We can use the Get-Content cmdlet to view the contents of this file:

We can see that the text file has four columns that contain information about the team, points, assists and rebounds for each player.

Suppose that we would like to only extract the team and the rebounds columns from this text file, which are located in index positions 0 and 3 of the file.

We can use the following syntax to do so:

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

The following screenshot shows how to use this syntax in practice:

PowerShell extract columns from text file

Notice that this returns only the columns in index positions 0 and 3 from the file named players.txt.

Note that you can specify any column numbers you’d like within the brackets to instead return different columns from the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Append to Text File
PowerShell: How to Combine Multiple Text Files into One File
PowerShell: How to Save Each Line of Text File as Array

Leave a Reply