用于计算单词、字符、空格和特殊符号数的 Shell 脚本
在本文中,我们将了解如何计算文本文件/输入字符串的单词、字符、空格和特殊符号的数量。给定一个文本文件,游览任务是计算单词、字符、空格和特殊符号的数量。因此,我们可以使用许多方法和工具来完成我们的任务。为了更好地理解,让我们举个例子:
Example:
Input text: GeeksforGeeks are best!
Output :
Number of Words = 3
Number of Characters = 24
Number of White Spaces =2
Number of Special Symbols = 2
Explanation:
words are { "GeeksforGeeks", "are", "best!!"}
Characters include number of white spaces(Space),special symbols and letter.
White Spaces are just spaces {' ',' '}
And Special Symbol are {'!','!'}
方法:
使用 厕所 命令。 wc 命令用于知道行数、字数、字节数和字符数等。
- 使用wc -w计算单词数。这里,“-w”表示我们正在计算单词。
- 使用wc -c计算字符数。这里,“-c”表示我们正在计算每个字符,包括空格。
- 使用以下语法计算字符串中的空格数:
Syntax: expr length “$text” – length `echo “$text” | sed “s/ //g”`
sed 命令用于操作文本,它代表流编辑器。在这里,我们使用 sed 使用sed “s/replace this with the whitespace//g”来找到白色的步调。在此语法中sed s指代替代, g指全局主义,此语法将搜索并替换整个文本中的每个空格。
使用以下正则表达式计算所有特殊字符。
Syntax: expr length “${text//[^\~!@#$&*()]/}”
外壳脚本:
#! /bin/bash
echo "Enter a String"
# Taking input from user
read text
# Counting words
word=$(echo -n "$text" | wc -w)
# Counting characters
char=$(echo -n "$text" | wc -c)
# Counting Number of white spaces (Here,specificly " ")
# sed "s/ change this to whitespace//g"
space=$(expr length "$text" - length `echo "$text" | sed "s/ //g"`)
# Counting special characters
special=$(expr length "${text//[^\~!@#$&*()]/}")
# Output
echo "Number of Words = $word"
echo "Number of Characters = $char"
echo "Number of White Spaces = $space"
echo "Number of Special symbols = $special"
输出: