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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM