[英]How can I print out the second word from each line of a file in powershell?
For example: sample.txt contains:例如:sample.txt 包含:
John Doe data
Jane Doe data
An the output would be: output 将是:
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).我试过
(Get-Content sample.txt).Split(' ')[1]
但这不起作用,因为它只打印第一行的第二个单词(数组的第二个元素)。
Output: Output:
Doe
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
读取的每一行上调用.Split()
(并索引到结果中),例如使用内部.ForEach()
方法:
(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:如果一行中的单词有可能被多个空格隔开,您可以改用 PowerShell 的
-split
运算符的一元形式:
(Get-Content sample.txt).ForEach({ (-split $_)[1] })
The streaming alternative, using the pipeline and the ForEach-Object
cmdlet :流媒体替代方案,使用管道和
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
.由于成员访问枚举,
.Split()
调用应用于Get-Content
返回的行数组的每一行。
Each .Split()
call in turn returns an array.每个
.Split()
调用依次返回一个数组。
Member-access enumeration concatenates these arrays to form a single, flat array containing the words across all lines.成员访问枚举将这些 arrays串联起来,形成一个单一的平面数组,其中包含跨所有行的单词。
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).然后,您的
[1]
索引仅应用一次,即应用于此平面数组,并仅返回其第二个元素(仅第一行的第二个单词)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.