How to count the number of tabs in each row using a shell script?

I need to write a script to count the number of tabs in each line of the file and print the output to a text file (e.g. output.txt).

How can I do it?

+8
source share
4 answers
awk '{print gsub(/\t/,"")}' inputfile > output.txt 
+15
source

If you treat \t as a field separator, there will be less \t in each line than there are fields:

 awk -F'\t' '{ print NF-1 }' input.txt > output.txt 
+5
source

This will give the total number of tabs in the file:

 od -c infile | grep -o "\t" | wc -l > output.txt 

This will give you the number of tabs per row:

 awk '{print gsub(/\t/,"")}' infile > output.txt 
+2
source

 sed 's/[^\t]//g' input.txt | awk '{ print length }' > output.txt 

Based on this answer .

+1
source

All Articles