Bootstrap FreeKB - PowerShell - Split fields at delimiter
PowerShell - Split fields at delimiter

Updated:   |  PowerShell articles

Let's say C:\Users\john.doe\Documents\example.txt contains the follow lines.

Hello World
Goodbye Earth

 

Get-Content can be used to read the content of a file. In this example, the lines are returned.

> Get-Content -path C:\Users\john.doe\Documents\example.txt
Hello World
Goodbye Earth

 

ForEach-Object can be used to create an index of the data. In this example, -split is followed by ' ', which means that a single white space will be used as the delimiter, and the items with index 0 will be returned.

> Get-Content -path C:\Users\john.doe\Documents\example.txt | ForEach-Object {
  ($_ -split ' ')[0]
}
Hello
Goodbye

 

Or, like this.

> Get-Content -path C:\Users\john.doe\Documents\example.txt | ForEach-Object {
  $item = $_ -split ' '
  Write-Host item 0 = $item[0]
  Write-Host item 1 = $item[1]
}
item 0 = Hello
item 1 = World
item 0 = Goodbye
item 1 = Earth

 

When dealing with unpredictible whitespace, use \s+.

> Get-Content -path C:\Users\john.doe\Documents\example.txt | ForEach-Object {
  ($_ -split '\s+')[1]
}
World
Earth

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 400155 in the box below so that we can be sure you are a human.