I have a file that is tab delimited. I would like a powershell script that counts the number of tabs in each line. I came up with this:
${C:\tabfile.txt} |% {$_} | Select-String \t | Measure-Object | fl count
it yields 3, Which is the number of lines in the file.
any pointers to what I'm doing wrong? I would like it to print a single number for each line in the file.
A couple issues with your code, but they all revolve around grouping / array management / nested loops.
gc test.txt | % { ($_ | select-string `t -all).matches | measure | select count }
First attempt, not very sophisticated:
gc .\tabfile.txt | % { ($_ -split "`t").Count - 1 }
Utilizing the fact here, that when I split the string at tab characters, I'll get an array with one more item than there are tabs in the line.
Another approach, avoiding splitting the lines:
gc .\tabfile.txt | % { ([char[]] $_ -eq "`t").Count }
Strings can be cast to char[]
(also there is the ToCharArray()
method), then I am using the fact that comparison operators work differently on collections, by returning all matching items, instead of a boolean. So the comparison there returns an array containing all tabs from the original line from which I just need to get the number of items.
And yet another option if you are running V2.
select-string \t c:\tabfile.txt -All |
%{"$($_.matches.count) tabs on $($_.LineNumber)"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With