Split string with PowerShell and do something with each token

后端 未结 4 1542
[愿得一人]
[愿得一人] 2020-12-04 23:27

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         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 00:02

    To complement Justus Thane's helpful answer:

    • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

      • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
        • Leading and trailing whitespace is ignored.
        • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
    • 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.

提交回复
热议问题