By1
By1

Reputation: 35

Q: find longest string using for loop (Bash)

Im learning bash, and I have an assignment where I need to iterate through a list of strings in bash using a for loop, and return the longest string.

This is what I've written:

max=-1
word=""
list=`cat random-text.txt | tr -s [:space:] " " | sed -r 's/([.* ])/\1\n/g' | grep -E "^a.*" | sed -r 's/(.*)[[:space:]]/\1/' | tr -s [:space:] " "`
                    for i in $list; do
                            int=`$i | wc -c`
                            if [ $int > $max ]; then
                                    max=$int
                                    word=$i
                            fi
                    done
                    echo The longest word in $infile that starts with $char is $i

that's probably a bit messy, but I'm having trouble using the for loop (I need the echo function at the end to return the longest string I have found iterating through the array.

** that's a part of a longer script I've written, I

Thanks in advance, much appreciated!

Upvotes: 1

Views: 505

Answers (1)

Armali
Armali

Reputation: 19395

for some reason, while I run this script I get an error which says: "Command 'an' not found

That's because you erroneously used $i | to feed the content of variable i to wc; correct is <<<$i instead (with Bash). But better use just int=${#i}.

Then in $int > $max the > is interpreted as an output redirection; the correct arithmetic comparison operator is -gt.

Finally you don't echo the longest word found, but rather the last processed one; change $i to $word there.

Upvotes: 1

Related Questions