PowerShell: How to Use ‘cut’ Equivalent


In a Unix/Linux environment, you can use the cut command to extract a specific column from a file.

To perform the equivalent task in PowerShell, you can use the following syntax:

Get-Content teams.txt | ForEach-Object { $_.split(" ")[1]}

This particular example will extract each of the values from the second column of the file named teams.txt.

Here is how this syntax works:

  • First, we use the Get-Content cmdlet to retrieve each line from the file.
  • Then, we use the ForEach-Object cmdlet to loop through each line in the file.
  • Then, we use the split command to split each line based on where spaces occur.
  • Lastly, we use [1] to extract the value from index position 1 (i.e. the second value) after the line has been split based on spaces.

You can change the value of 1 to a different number to instead extract a different column from the file.

You can also change the delimiter used in the split command to instead split the file based on a different delimiter.

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

Example: How to Use Equivalent of ‘cut’ Command in PowerShell

Suppose that we have a file named teams.txt that contains information about various basketball teams.

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

Now suppose that we would like to extract the values from the second column of the file, which contain the team names.

We can use the following syntax to do so:

Get-Content teams.txt | ForEach-Object { $_.split(" ")[1]}

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

PowerShell cut equivalent

Notice that this returns each of the values from the second column of the file.

Note that we could replace 1 with a different number to instead retrieve a different column.

For example, we could use a value of 0 to instead extract values from the first column of the file:

Get-Content teams.txt | ForEach-Object { $_.split(" ")[0]}

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

Notice that this returns each of the values from the first column of the file.

Related Tutorials

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

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties
PowerShell: How to Use Where-Object in List

Leave a Reply