bash 计算Linux中制表符的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11035180/
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 02:29:58  来源:igfitidea点击:

count number of tab characters in linux

bashunixcshgrep

提问by ravi

I want to count the numbers of hard tab charactersin my documents in unix shell.

我想hard tab characters在 unix shell 中计算我的文档中的数量。

How can I do it?

我该怎么做?

I tried something like

我试过类似的东西

grep -c \t foo

grep -c \t foo

but it gives counts of t in file foo.

但它在文件 foo 中给出了 t 的计数。

回答by William Pursell

Use tr to discard everything except tabs, and then count:

使用 tr 丢弃除制表符以外的所有内容,然后计数:

< input-file tr -dc \t | wc -c

回答by chepner

Bash uses a $'...'notation for specifying special characters:

Bash 使用一种$'...'表示法来指定特殊字符:

grep -c $'\t' foo

回答by Joni

You can insert a literal TAB character between the quotes with Ctrl+V+TAB.

您可以使用Ctrl+V+在引号之间插入文字 TAB 字符TAB

In general you can insert any character at all by prefixing it with Ctrl+V; even control characters such as Enteror Ctrl+Cthat the shell would otherwise interpret.

通常,您可以通过添加前缀来插入任何字符Ctrl+V;甚至控制字符,如EnterCtrl+Cshell 否则会解释。

回答by dogbane

Use a perl regex (-Poption) to grep tab characters.

使用 perl 正则表达式(-P选项)来 grep 制表符。

So, to count the number of tab characters in a file:

因此,要计算文件中制表符的数量:

grep -o -P '\t' foo | wc -l

回答by glenn Hymanman

You can use awk in a tricky way: use tab as the record separator, then the number of tab characters is the total number of records minus 1:

你可以用一个技巧来使用 awk:使用制表符作为记录分隔符,那么制表符的数量就是记录总数减 1:

ntabs=$(awk 'BEGIN {RS="\t"} END {print NR-1}' foo)

回答by LukeShu

My first thought was to use sedto strip out all non-tab characters, then use wcto count the number of characters left.

我的第一个想法是用来sed去除所有非制表符,然后wc用来计算剩余的字符数。

< foo.txt sed 's/[^\t]//g' | wc -c

However, this also counts newlines, which sedwon't touch because it is line-based. So, let's use trto translate all the newlines into spaces, so it is one line for sed.

但是,这也计算换行符,它sed不会触及,因为它是基于行的。因此,让我们使用tr将所有换行符转换为空格,因此sed.

< foo.txt tr '\n' ' ' | sed 's/[^\t]//g' | wc -c

Depending on your shell and implementation of sed, you may have to use a literal tab instead of \t, however, with Bash and GNU sed, the above works.

根据您的 shell 和 的实现sed,您可能必须使用文字选项卡而不是\t,但是,对于 Bash 和 GNU sed,上述工作是有效的。