简体   繁体   中英

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? ( 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:

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 . What the awk does is:

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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