count characters in multiple files and sort

I am trying to count a special character in several thousand files and sort the result according to the number the character occured in each files.

files:
1.txt
2.txt
3.txt

files look like:
ABCDEFGHABBBACF

I want the number of B in each file and a result file that lists the occurence of B in each file.

result:
3.txt 4
1.txt 1
2.txt 3

I have tried:
ls *txt | xargs grep -c "B"
from there I want to pipe the output into 'sort'
But 'grep -c' gives only the number of lines, not the number of characters.

Try this in directory containing those thousands of files:

perl -n0e '@n=/B/g;print "$ARGV ",$#n+1,"\n"' * | sort -rnk2 > result
1 Like
$ cat sample1.txt
ABCDEFAB ASK SDFKJDF

$ cat sample1.txt | sed s/./\&~/g | tr "~" "\n" | grep "B" | wc -l
2
1 Like

Thanks a lot bartus11.
The script works perfectly fine.
Best regards

# cat file
ABCDDEBFGFDDSD
BBBBZYZWWDILSAASAA
BBBBZYZWWDILSAASAA

try search "B" ...

# sed 's/[^B]//g' file|sed ':a;$!N;s/\n//;ta'|sed -e 's/B/&\n/g'|sed -ne '/^$/!p'|sed -n '$='
10
# awk -F'B' '{n+=NF-1}END{print n}' file
10
# grep -o "B" file |wc -l
10
# tr -cd 'B' <file| wc -c
10

regards
ygemici

1 Like