bash 如何使用shell脚本计算每行中的选项卡数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15517363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:55:15  来源:igfitidea点击:

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

linuxbashshell

提问by bcd

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).

我需要编写一个脚本来计算文件每一行中的选项卡数量并将输出打印到文本文件(例如,output.txt)。

How do I do this?

我该怎么做呢?

回答by bcd

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

回答by chepner

If you treat \tas the field delimiter, there will be one fewer \tthan fields on each line:

如果您将其\t视为字段分隔符,则\t每行将少于一个字段:

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

回答by Rostyslav

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

回答by Chirag Bhatia - chirag64

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

Based on this answer.

基于这个答案