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
复制代码

 

posted @   小鲨鱼2018  阅读(1132)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-04-15 R语言中sample函数
2021-04-15 linux系统awk命令求一行值的和、平均值、最大值和最小值
2021-04-15 linux系统中awk命令求一列值的最大值、最小值、和及平均值
2021-04-15 R语言中找交集、并集、找不同、判断是否相同
2021-04-15 R语言中unique函数
2021-04-15 linux系统中将一列数据转换为指定的行
2021-04-15 linux系统中实现文本转置
点击右上角即可分享
微信分享提示