5 ms·
One difference in usage of PWSH I can't wrap my head around is when I want to do something akin to: grep -rl $pattern | $othercommand So far I've got this
by Jestar342 6y ago
One difference in usage of PWSH I can't wrap my head around is when I want to do something akin to:
grep -rl $pattern | $othercommand
So far I've got this (deliberately avoiding aliases for this example) in the above grep's command's stead:
Get-ChildItem -Recurse -Path * | Select-String $pattern
But I just cannot fathom how to break from the table format to pass the lines to $othercommand.
How does one pass a pwsh list to a single command? Using %{}/For-Each {} wouldn't work because it would invoke $othercommand for each line.
- GSGBen 6y agoEverything in powershell is an object, but sometimes the output format doesn't make it clear. Select-String basically returns a match object with some nested results, but the output formatting makes it awkward to see. Pipe it to | format-list * to investigate it, and you'll see a bunch of members. In this case if what you want is just the matched string, you want to expand the `Matches` property of the object, then expand the value property of each of those. In this case the term 'expand' is key: if you just use `select` it'll return you the property, name and all. Use `-expand` to return the plain array. So something like: Get-ChildItem -Recurse -Path * | Select-String $pattern | select -expand matches | select -expand value which you can then use how you like. An alternate form is (Get-ChildItem -Recurse -Path * | Select-String $pattern).Matches.Value because the . notation for member access works on all items in an array (Matches in this case).
- asimops 6y agoSince Powershell isn't working on text but on objects, you might just want to use grep. Anyways, this should reproduce the output of grep in powershell: Get-ChildItem -Recurse -File | Select-String "$pattern" -List -SimpleMatch -CaseSensitive | Select-Object -ExpandProperty path You will want to only search in files for this to not ouput some lines of InputStream if there is a match in the actual path. If $pattern is an actual regex you will want to drop SimpleMatch. In case you want some proper powershell objects you might want to pipe this into Get-Item.
- jolux 6y agoI don't think I entirely understand the question, is $othercommand doing something with all of the lines together?
- Jestar342 6y agoYes, for example other command may be (and often is) fzf followed by yet another command to exec on the chosen file.