使用 PowerShell 拆分字符串并对每个令牌执行某些操作 [英] Split string with PowerShell and do something with each token
问题描述
我想在空格上分割管道的每一行,然后在自己的行上打印每个标记.
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 someFileInsteadOfAPipe).split(" ")
但我想要更大的灵活性.我希望能够对每个令牌做任何事情.(我曾经在 Unix 上使用 AWK,我正在尝试获得相同的功能.)
But I want more flexibility. I want to be able to do just about anything with each token. (I used to use AWK on Unix, and I'm trying to get the same functionality.)
我目前拥有:
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, only prints the first token. Is there a way for me to for-each over the tokens, printing each in turn?
另外,%{$data = $_.split(" ");Write-Output "$($data[0])"}
部分我从博客中得到的,我真的不明白我在做什么或语法是如何工作的.
Also, the %{$data = $_.split(" "); Write-Output "$($data[0])"}
part I got from a blog, and I really don't understand what I'm doing or how the syntax works.
我想用谷歌搜索它,但我不知道该怎么称呼它.请帮我一两句话到谷歌,或者一个链接向我解释 %
和所有 $
符号的作用,以及开头的意义和右括号.
I want to google for it, but I don't know what to call it. Please help me out with a word or two to Google, or a link explaining to me what the %
and all the $
symbols do, as well as the significance of the opening and closing brackets.
我意识到我实际上不能使用 (cat someFileInsteadOfAPipe).split(" ")
,因为文件(或更好的输入管道)包含不止一行.
I realise I can't actually use (cat someFileInsteadOfAPipe).split(" ")
, since the file (or preferable incoming pipe) contains more than one line.
关于一些答案:
如果您使用 Select-String
来过滤在标记化之前的输出,您需要记住 Select-String
命令的输出不是字符串的集合,而是 MatchInfo
对象的集合.要获得要拆分的字符串,您需要访问 MatchInfo
对象的 Line
属性,如下所示:
If you are using Select-String
to filter the output before tokenizing, 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 get to the string you want to split, you need to access the Line
property of the MatchInfo
object, like so:
cat someFile | Select-String "keywordFoo" | %{$_.Line.Split(" ")}
推荐答案
"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:
%
是 ForEach 的别名-对象
.括号内的任何内容都对其接收到的每个对象运行一次.在这种情况下,它只运行一次,因为您发送的是单个字符串.
%
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(" ")
正在获取当前变量并将其拆分为空格.当前变量将是 ForEach
当前正在循环的任何内容.
$_.Split(" ")
is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach
.
这篇关于使用 PowerShell 拆分字符串并对每个令牌执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!