【问题标题】:How can I print out the second word from each line of a file in powershell?如何在 powershell 中打印出文件每一行的第二个单词?
【发布时间】:2022-11-26 04:58:48
【问题描述】:

例如:sample.txt 包含:

John Doe data
Jane Doe data

输出将是:

Doe
Doe

我试过 (Get-Content sample.txt).Split(' ')[1] 但它不起作用,因为它只打印第一行的第二个单词(数组的第二个元素)。

输出:

Doe

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您需要调用.Split()(并索引到结果中)在每一行由Get-Content阅读,例如intrinsic .ForEach() method:

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

    如果有机会多空格分隔一行中的单词,您可以使用 PowerShell 的一元形式 -split操作员反而:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2019-05-05
      相关资源
      最近更新 更多