1

I have this code in bash. I wanted to ask, how can I change this code that for example when if gets to the word Aaa: ----> the output of the length of this word will be 3 and not 4 (I want it to ignore other chars and only count the letters). Thanks for the help!

#!/bin/bash

words=$(tr -s '[.,: ] ' '\n' < "$1")
longest_length=0
for word in $words
do
current_length=${#word}
if ((current_length > longest_length))
    then
        longest_length=$current_length
        longest_word=$word
    fi
done

echo 'The longest word is %s and its length is %d.\n' "$longest_word" "$longest_length" 
Michelle
  • 41
  • 5

2 Answers2

1

I suggest to replace '[.,: ] ' with '[a-zA-Z] ' and replace echo with printf.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

Some alternative tools:

$ echo "A:a:a:b-ed5f^ht" |grep -o '[a-zA-Z]' |wc -l
9

$ echo "A:a:a:b-ed5f^ht" |awk -F'[a-zA-Z]' '{print NF-1}' 
9
George Vasiliou
  • 6,130
  • 2
  • 20
  • 27