简体   繁体   English

计算 Linux/unix 中所有行中特定列的字符数

[英]Counting characters for specific column across all lines in Linux/unix

How can I count number of characters for specific column in tsv file, while this column contains sentences and not a single string?如何计算 tsv 文件中特定列的字符数,而此列包含句子而不是单个字符串? ( I want to count for each line in the column). (我想计算列中的每一行)。

for example: (in case of csv) counting number of characters for the second field/column:例如:(在 csv 的情况下)计算第二个字段/列的字符数:

Input:输入:

ab, an apple  
ac, not juice   
ad, I like  

Output:输出:

ab, an apple , 7  
ac, not juice, 8  
ad, I like, 5  

Does this work for you?这对你有用吗?

awk -F, '{printf "%s,%s,%s\n",$1,$2,length(gensub(/ /, "", "g", $2))}' sleiman.txt

I gave the file the name sleiman.txt .我将文件命名为sleiman.txt What the awk does is: awk 的作用是:

  • take , as an input field separator,作为输入字段分隔符
  • print the 1st and 2nd field unchanged打印第一个和第二个字段不变
  • strip the spaces out of the 2nd field, count the number of remaining characters, print it after the 2nd filed从第二个字段中去除空格,计算剩余字符数,在第二个字段后打印

So the output is then:所以输出是:

awk -F, '{printf "%s,%s,%s\n",$1,$2,length(gensub(/ /, "", "g", $2))}' sleiman.txt
ab, an apple  ,7
ac, not juice   ,8
ad, I like  ,5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM