Oneliner for counting the number of tabs in each line of a file

I have a tab delimited file. I would like the powershell script to count the number of tabs in each row. I came up with this:

${C:\tabfile.txt} |% {$_} | Select-String \t | Measure-Object | fl count 

it gives 3, namely the number of lines in the file.

any pointers to what i am doing wrong? I would like it to print one number for each line in the file.

+4
source share
4 answers

A couple of problems with your code, but they all revolve around grouping / array control / nested loops.

 gc test.txt | % { ($_ | select-string `t -all).matches | measure | select count } 
  • After reading the text file in the lines, you need to wrap the rest of the pipeline in the script block. Otherwise, the downstream cmdlets cannot tell which elements came from the "current" line. The PS pipeline is the whole thing about objects one after another - there is no concept of nested arrays or the state of an iterator or anything else - blind enumeration.
  • You need to specify -AllMatches, otherwise select-string will stop as soon as it finds the first match on each line. Then you need to get the Matches property from its nominal result set to get the โ€œinternal result setโ€ of this inline match.
+6
source

The first attempt, not very difficult:

 gc .\tabfile.txt | % { ($_ -split "`t").Count - 1 } 

Using the fact that when I split the string into tabs, I get an array with one more element than there are tabs in the string.

Another approach, avoiding line breaks:

 gc .\tabfile.txt | % { ([char[]] $_ -eq "`t").Count } 

Strings can be added to char[] (there is also a ToCharArray() method), then I use the fact that comparison operators work differently in collections, returning all matching elements instead of boolean ones. Thus, the comparison there returns an array containing all the tabs from the original string, from which I just need to get the number of elements.

+5
source

And one more option if you use V2.

 select-string \tc:\tabfile.txt -All | %{"$($_.matches.count) tabs on $($_.LineNumber)"} 
+4
source

Another option:

 $content = Get-Content file.txt | Out-String [regex]::matches($content,"\t").count 
+2
source

All Articles