Can you tell I'm cleaning out open windows on my laptop this morning?

Here's a line of PowerShell that uses Select-String to replicate grep piping just the found lines (no file name prefix on the results, case-insensitive matching) to a file:

select-string -path .\bank.controller.js -pattern "questionbuilderstate" | Select -ExpandProperty Line > c:\temp\qbs.txt

PowerShell returns objects, and you have to pull out just the result to write to the file. Otherwise you have tons of cruft in your results like this...

bank.controller.js:352: vm.questionBuilderState.selectQuestion(question);

That stinks.

The above command removes the file name and line number.


Bonus code: How to dos2unix (I installed on an M1 Mac with Big Sur via brew) recursively on macOS:

find ./ -type f -print0 | xargs -0 dos2unix --


UPDATE: Wow, grepping with Select-String was a disaster. In practice, there are LOTS of gotchas.

I wanted to find a string in a single file and put the results into a file. I tried piping the normal way with > out.txt, but ran into an annoying issue where Powershell wraps long lines by default in text output. When you're looking at log files that might have 40k [sic] characters in a line, that gives you an absolute mess.

Why? WHY??!!!

(One comment on SO suggests it's b/c "output gets formatted for a certain width of monitor" and even gives a source for that claim. Please heavens no. Why do you take a line and, without any input, turn it into something else? Leave -width for those who want it, for crimminy's sake.)

Anyhow, the solution is to add an explicit Out-File call with a giant -width value.

Here's what I ended up using for my call to write results to out.txt:

Get-ChildItem -Path '.\my file name.txt' |Select-String -Pattern "Some.Nuget.Library\\1.0.0" |Out-File -width 99999 out.txt

That's... that's not discoverable at all. I mean, it's not impossible to find, but that > out.txt decides it should wrap a command that line breaks by default is a horrible alias. At least alias that to unlimited width lines.

I can't recall why I stopped using -path in Select-String, but something wacky was going on there too. I think.

Hope that helps.

Labels: , ,