计算字符,单词,单词的长度和句子的总长度 [英] Counting characters, words, length of the words and total length in a sentence

查看:166
本文介绍了计算字符,单词,单词的长度和句子的总长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个包含句子的脚本,并打印单词数,字符数(不包括空格),每个单词的长度和长度.我知道存在wc -m来计数单词中的字符数,但是如何在脚本中使用它呢?

I have to write a script that takes a sentence and prints the word count, character count (excluding the spaces), length of each word and the length. I know that there exist wc -m to counter number of characters in the word, but how to make use of it in script?

#!/bin/bash

mystring="one two three test five"
maxlen=0;
for token in $mystring; do
  echo -n "$token: ";
  echo -n $token | wc -m;
    if [ ${#token} -gt $maxlen ]; then 
      maxlen=${#token}; fi;
done

echo "--------------------------";
echo -n "Total words: ";
echo "$mystring" | wc -w;
echo -n "Total chars: ";
echo "$mystring" | wc -m;
echo -n "Max length: "; 
echo $maxlen

推荐答案

围绕Jaypal Singh的答案

riffing on Jaypal Singh's answer:

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
jcomeau@intrepid:~$ echo -n "lengths of words: "; i=0; for token in $mystring; do echo -n "${#token} "; i=$((i+1)); done; echo; echo "word count: $i"
lengths of words: 3 3 5 4 4 
word count: 5
jcomeau@intrepid:~$ echo -n "maximum string length: "; maxlen=0; for token in $mystring; do if [ ${#token} -gt $maxlen ]; then maxlen=${#token}; fi; done; echo $maxlen
maximum string length: 5

这篇关于计算字符,单词,单词的长度和句子的总长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆