Finding the longest word in a text file

Another solution:

for item in  $(cat "$infile"); do
  length[${#item}]=$item          # use word length as index
done
maxword=${length[@]: -1}          # select last array element

printf  "longest word '%s', length %d" ${maxword} ${#maxword}

Normally, you'd want to use a while read loop instead of for i in $(cat), but since you want all the words to be split, in this case it would work out OK.

#!/bin/bash
longest=0
for word in $(<so.txt)
do
    len=${#word}
    if (( len > longest ))
    then
        longest=$len
        longword=$word
    fi
done
printf 'The longest word is %s and its length is %d.\n' "$longword" "$longest"

bash one liner.

sed 's/ /\n/g' YOUR_FILENAME | sort | uniq | awk '{print length, $0}' | sort -nr | head -n 1
  1. read file and split the words (via sed)
  2. remove duplicates (via sort | uniq)
  3. prefix each word with it's length (awk)
  4. sort the list by the word length
  5. print the single word with greatest length.

yes this will be slower than some of the above solutions, but it also doesn't require remembering the semantics of bash for loops.


longest=""
for word in $(cat so.txt); do
    if [ ${#word} -gt ${#longest} ]; then
        longest=$word
    fi
done

echo $longest

Tags:

Linux

Unix

Bash