Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the longest word in a text file

Tags:

linux

bash

unix

I am trying to make a a simple script of finding the largest word and its number/length in a text file using bash. I know when I use awk its simple and straight forward but I want to try and use this method...lets say I know if a=wmememememe and if I want to find the length I can use echo {#a} its word I would echo ${a}. But I want to apply it on this below

for i in `cat so.txt` do

Where so.txt contains words, I hope it makes sense.

like image 816
Mildred Shimz Avatar asked Jan 22 '12 16:01

Mildred Shimz


People also ask

How do you find the longest string in a text file using Python?

The open() is a function to open a text file. Set “len” as key to max function. It will find the longest line from file in Python Program.

How do you find the longest word in Java?

if(large. length() < words[k]. length()) large = words[k];


Video Answer


2 Answers

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.

like image 128
BlessedKey Avatar answered Oct 01 '22 18:10

BlessedKey


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"
like image 23
Dennis Williamson Avatar answered Oct 01 '22 18:10

Dennis Williamson