Split string with PowerShell and do something with each token

后端 未结 4 1526
[愿得一人]
[愿得一人] 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:00

    Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

    $test = '   One      for the money   '
    $option = [System.StringSplitOptions]::RemoveEmptyEntries
    $($test.split(' ',$option)).foreach{$_}
    

    This will come out as:

    One
    for
    the
    money
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 00:06
    "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:

    % 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(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach.

    0 讨论(0)
  • 2020-12-05 00:09

    -split outputs an array, and you can save it to a variable like this:

    $a = -split 'Once  upon    a     time'
    $a[0]
    
    Once
    

    Another cute thing, you can have arrays on both sides of an assignment statement:

    $a,$b,$c = -split 'Once  upon    a'
    $c
    
    a
    
    0 讨论(0)
提交回复
热议问题