Home > Back-end >  How can I print out the second word from each line of a file in powershell?
How can I print out the second word from each line of a file in powershell?

Time:11-29

For example: sample.txt contains:

John Doe data
Jane Doe data

An the output would be:

Doe
Doe

I've tried (Get-Content sample.txt).Split(' ')[1] but that doesn't work since it prints the second word of the first line only (second element of the array).

Output:

Doe

CodePudding user response:

You need to call .Split() (and index into the result) on each line read by Get-Content, such as with the intrinsic .ForEach() method:

(Get-Content sample.txt).ForEach({ $_.Split(' ')[1] })

If there's a chance that multiple spaces separate the words on a line, you can use the unary form of PowerShell's -split operator instead:

(Get-Content sample.txt).ForEach({ (-split $_)[1] })

The streaming alternative, using the pipeline and the ForEach-Object cmdlet:

Get-Content sample.txt | ForEach-Object { $_.Split(' ')[1] }

As for what you tried:

(Get-Content sample.txt).Split(' ')[1]
  • Thanks to member-access enumeration, the .Split() call is applied to each line of the array of lines returned by Get-Content.

  • Each .Split() call in turn returns an array.

  • Member-access enumeration concatenates these arrays to form a single, flat array containing the words across all lines.

  • Your [1] index is then applied only once, namely to this flat array, and returns its second element only (only the first line's second word).

  • Related