Longestword In A Dictionary

Find the longest word in a file (e.g. dictionary file)

Find the length of the longest word in a file (every line only contains 1 word)

wc -L

AWK Approach: Print the longest word in a file (every line only contains 1 word)

b96123@linux13 [~/workspace/sysprog/hw1] awk '{ if ( length > a ) { a = length; b=$0 }} END { print b }' testdata/knuth_words.txt 
antidisestablishmentarianism

AWK | Shell Approach (Find the length of the longest word in a file (every line only contains 1 word)

b96123@linux13 [~/workspace/sysprog/hw1]  awk '{ if ( length >a ) { a = length; b=$0 }}END{ print b }' testdata/testdata.txt  | wc -L 
18
b96123@linux13 [~/workspace/sysprog/hw1]

Shell Approach: Print the longest word in a file (1 line contains n-words) (very slow)

read< <(sort -rn <(for w in $(<file);do w="${w//[,.:\"\'()<>]}"
printf "%d %s\n" "${#w}" "$w";done));printf "%s\n" "${REPLY#* }"

AWK Approach: Print the longest word in a file (1 line contains n-words)

awk 'BEGIN{ l=0}
   {  
      for ( i=1 ;i<=NF;i++){
         gsub(/[[:punct:]]/,"",$i)
            if (length($i) >l ) { 
            l=length($i)
            f=$i         
         }         
      }      
   }
   END{
      print l, f
   }' "file"

Start it:

b96123@linux13 [~/workspace/sysprog/hw1] ./findword.awk
28 antidisestablishmentarianism

Sources: http://www.unix.com/unix-advanced-expert-users/43360-sed-get-longest-word.html

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License