Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of characters in each line of a file, excluding a list of specific characters?

Tags:

bash

How can I count how many characters appear within a file, minus those from a specific list. Here is an example file:

你好吗?
我很好,你呢?
我也很好。

I want to exclude any occurrences of , , and from the count. The output would look like this:

3
5
4
like image 231
Village Avatar asked Dec 25 '22 17:12

Village


2 Answers

A pure bash solution:

while IFS= read -r l; do
    l=${l//[?,。]/}
    echo "${#l}"
done < file
like image 52
gniourf_gniourf Avatar answered Apr 19 '23 23:04

gniourf_gniourf


Try

sed 's/[,。?]//g' file | perl -C -nle 'print length'

The sed part removes unwanted characters, and the perl part counts the remaining characters.

like image 34
Hari Menon Avatar answered Apr 20 '23 01:04

Hari Menon