How to join array in pipe
Asked Answered
B

3

13

I wish to join the result from a pipe.

I tried using -join

PS> type .\bleh.log | where { $_ -match "foo"} | select -uniq | $_ -join ','

But that give me this error :/

Expressions are only allowed as the first element of a pipeline.

Bessel answered 18/11, 2015 at 8:50 Comment(0)
W
13

You could try this :

@(type .\bleh.log | where { $_ -match "foo"} | select -uniq) -join ","

You would need a Foreach-Object (alias %) after the last pipe to have the $_ variable available but it wouldn't help since it holds a single cell value (for each loop iteration).

Washwoman answered 18/11, 2015 at 8:56 Comment(3)
Isn't it possible to keep it as a one liner?Gensmer
Answer edited. But if you need a real CSV file, there are dedicated cmdlets, like Export-Csv.Washwoman
I just need to c/p the result, so the above is just what I want :)Gensmer
A
0

this code search the file for the characters "ya" and returns a unique list as an array. It then takes the array elements and joins them into a string separated by a comma

 @(type requirements.txt | where {($_).Trim() -match "ya"} | select -Unique) -join ","
Adhamh answered 23/3, 2023 at 20:7 Comment(0)
D
0

As an alternative PowerShell 6.2 and above comes with the Join-String cmdlet:

Get-Content .\bleh.log |
    Where-Object { $_ -match 'foo' } |
    Select-Object -Unique |
    Join-String -Separator ','

A simple but not very reliably non-advanced function for Windows PowerShell could be:

function pipejoin {
    @($input) -join $args[0]
}

0..10 | pipejoin ','
Dent answered 23/3, 2023 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.