user1960932
user1960932

Reputation:

How to count number of tabs in each line using shell script?

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

How do I do this?

Upvotes: 17

Views: 16154

Answers (4)

bcd
bcd

Reputation: 454

awk '{print gsub(/\t/,"")}' inputfile > output.txt

Upvotes: 26

chepner
chepner

Reputation: 531355

If you treat \t as the field delimiter, there will be one fewer \t than fields on each line:

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

Upvotes: 13

Rostyslav
Rostyslav

Reputation: 353

This will give the total number of tabs in file:

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

This will give you number of tabs line by line:

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

Upvotes: 2

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4526

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

Based on this answer.

Upvotes: 2

Related Questions