I want to split each line of a pipe on spaces, and then print each token on its own line.
I realise that I can get this result using:
(cat someFileIn
Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:
$test = ' One for the money '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}
This will come out as:
One
for
the
money
To complement Justus Thane's helpful answer:
As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.
-split '...'
), -split
behaves like awk
's default field splitting, which means that:
In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object
cmdlet became available: the .ForEach()
array (collection) method, as described in this blog post (alongside the .Where()
method, a more powerful, expression-based alternative to Where-Object
).
Here's a solution based on these features:
PS> (-split ' One for the money ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]
Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One
and for
were treated as a single separator.
"Once upon a time there were three little pigs".Split(" ") | ForEach {
"$_ is a token"
}
The key is $_
, which stands for the current variable in the pipeline.
About the code you found online:
%
is an alias for ForEach-Object. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.
$_.Split(" ")
is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach
.
-split outputs an array, and you can save it to a variable like this:
$a = -split 'Once upon a time'
$a[0]
Once
Another cute thing, you can have arrays on both sides of an assignment statement:
$a,$b,$c = -split 'Once upon a'
$c
a