linux中如何统计文本字符的总个数
1、测试数据
[root@centos7 test3]# ls
test.txt
[root@centos7 test3]# cat test.txt
deet
dggh
df
2、awk实现
[root@centos7 test3]# ls test.txt [root@centos7 test3]# cat test.txt deet dggh df [root@centos7 test3]# awk '{print length}' test.txt 4 4 2 [root@centos7 test3]# awk '{print length}' test.txt | awk 'BEGIN{sum = 0} {sum += $1} END {print sum}' 10
或者:
[root@centos7 test3]# ls test.txt [root@centos7 test3]# cat test.txt deet dggh df [root@centos7 test3]# paste -d "" -s test.txt deetdgghdf [root@centos7 test3]# paste -d "" -s test.txt | awk '{print length}' 10
3、wc + awk命令实现
[root@centos7 test3]# ls test.txt [root@centos7 test3]# cat test.txt deet dg er df e [root@centos7 test3]# wc test.txt ## 依次输出行数、单词数、字符数(包含空格和换行符)、文件名 3 5 17 test.txt
[root@centos7 test3]# ls test.txt [root@centos7 test3]# cat test.txt deet dg er df e [root@centos7 test3]# wc -l test.txt ## 行数 3 test.txt [root@centos7 test3]# wc -w test.txt ## 单词数 5 test.txt [root@centos7 test3]# wc -c test.txt ## 字符数(包含空格和换行符) 17 test.txt
统计字符数(不包含空格和换行符):
[root@centos7 test3]# ls test.txt [root@centos7 test3]# cat test.txt deet dg er df e [root@centos7 test3]# sed 's/[\t ]*//g' test.txt deet dger dfe [root@centos7 test3]# sed 's/[\t ]*//g' test.txt | wc 3 3 14 [root@centos7 test3]# sed 's/[\t ]*//g' test.txt | wc | awk '{print $3 - $1}' 11
4、awk实现
[root@centos7 test2]# ls a.txt [root@centos7 test2]# cat a.txt eft sfge fjddg eiy [root@centos7 test2]# awk 'BEGIN{len = 0} {len += length($0)} END {print len}' a.txt 15