Split a string using PowerShell and do something with each token

I want to break each line into spaces, and then print each token in its line.

I understand that I can get this result using:

(cat someFileInsteadOfAPipe).split(" ") 

But I want more flexibility. I want to be able to do anything with every token. (I used AWK on Unix, and I'm trying to get the same functionality.)

I currently have:

 echo "Once upon a time there were three little pigs" | %{$data = $_.split(" "); Write-Output "$($data[0]) and whatever I want to output with it"} 

Which, obviously, prints only the first token. Is there a way for me - for each token, to print each in turn?

In addition, part %{$data = $_.split(" "); Write-Output "$($data[0])"} %{$data = $_.split(" "); Write-Output "$($data[0])"} , which I got from the blog, and I really donโ€™t understand what I am doing or how the syntax works.

I want to use Google for this, but I do not know what to call it. Please help me with a word or two on Google or a link explaining to me what the % and all $ characters mean, as well as the meaning of opening and closing brackets.

I understand that in fact I canโ€™t use (cat someFileInsteadOfAPipe).split(" ") , since the file (or the preferred input channel) contains more than one line.

Regarding some answers:

If you use Select-String to filter the output before tokenization, you need to keep in mind that the output of the Select-String command is not a collection of strings, but a collection of MatchInfo objects. To go to the line you want to split, you need to access the Line property of the MatchInfo object, for example:

 cat someFile | Select-String "keywordFoo" | %{$_.Line.Split(" ")} 
+47
string tokenize powershell
Jul 05 2018-12-12T00:
source share
1 answer
 "Once upon a time there were three little pigs".Split(" ") | ForEach { Write-Host "$_ is a token" } 

The key is $_ , which indicates the current variable in the pipeline.

About the code you found online:

% is an alias for ForEach-Object . Everything enclosed in parentheses is run once for each object that it receives. In this case, it only works once, because you send it one line.

$_.Split(" ") takes the current variable and breaks it into spaces. The current variable will be what is currently looping on ForEach .

+97
Jul 05 2018-12-12T00:
source share
โ€” -



All Articles