UNIX - 计数每行/场人物的出现 [英] unix - count occurrences of character per line/field

查看:75
本文介绍了UNIX - 计数每行/场人物的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于像这样的数据文件(即stores.dat文件)

  SID | storeNo |纬度|经度
2TT | 1 | -28.0372000t0 | 153.42921670
9 |2吨| -33tt.85t09t0000 | 15t1.03274200

什么是,将返回每行的T字?

中出现的次数命令

如。将返回:

 算LINENUM
   4 1
   3 2
   6 3


此外,通过事件的数量做外地的是返回结果如下命令?

如。第2列和字符'T'输入

 算LINENUM
   1 1
   0 2
   1 3

如。列3和字符'T'输入

 算LINENUM
   2 1
   1 2
   4 3


解决方案

要计算每行的字符,你可以做的发生:

 的awk -F| 'BEGIN {打印伯爵,LINENUM} {打印GSUB(/ T /,)\\ t的NR}'文件
算上LINENUM
4 1
3 2
6 3

要计算每场/列的字符,你可以做的发生:

第2列:

 的awk -F| -v FLD = 2'BEGIN {打印伯爵,LINENUM} {打印GSUB(/ T /,,$ FLD)\\ t的NR}'文件
算上LINENUM
1 1
0 2
1 3

第3列:

 的awk -F| -v FLD = 3'BEGIN {打印伯爵,LINENUM} {打印GSUB(/ T /,,$ FLD)\\ t的NR}'文件
算上LINENUM
2 1
1 2
4 3


  • GSUB()函数的返回值是由替代的数量。因此,我们使用该打印数。

  • NR 持有的行号,所以我们用它来打印的行号。

  • 对于特定领域的印刷事件,我们创建了一个变量 FLD ,把我们想从提取计数场数。

Given a file with data like this (ie stores.dat file)

sid|storeNo|latitude|longitude
2tt|1|-28.0372000t0|153.42921670
9|2t|-33tt.85t09t0000|15t1.03274200

What is the command that would return the number of occurrences of the 't' character per line?

eg. would return:

count   lineNum
   4       1
   3       2
   6       3


Also, to do it by count of occurrences by field what is the command to return the following results?

eg. input of column 2 and character 't'

count   lineNum
   1       1
   0       2
   1       3

eg. input of column 3 and character 't'

count   lineNum
   2       1
   1       2
   4       3

解决方案

To count occurrence of a character per line you can do:

awk -F'|' 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"") "\t" NR}' file
count lineNum
4       1
3       2
6       3

To count occurrence of a character per field/column you can do:

column 2:

awk -F'|' -v fld=2 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"",$fld) "\t" NR}' file
count lineNum
1       1
0       2
1       3

column 3:

awk -F'|' -v fld=3 'BEGIN{print "count", "lineNum"}{print gsub(/t/,"",$fld) "\t" NR}' file
count lineNum
2       1
1       2
4       3

  • gsub() function's return value is number of substitution made. So we use that to print the number.
  • NR holds the line number so we use it to print the line number.
  • For printing occurrences of particular field, we create a variable fld and put the field number we wish to extract counts from.

这篇关于UNIX - 计数每行/场人物的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆