0

I wrote a bit of code to find the two longest words from the text files that you provide it with. The code itself finds those words without problem, however when I then want to print those words both echo , echo -e and printf mess up the order of obly the last line I try to print, all the others are printed just fine. I switched from echo to printf because I read that echo wasn't very reliable. Both are just fine for me.

Here's the code:

#!/bin/bash

printf "Enter files to be scanned: \n"
read -a files
printf "The provided files to be scanned are : ${files[*]}\n"

LongestWord=
secLongestWord=
lenLW=0
lensecLW=0
for file in "${files[@]}"; do
        for word in $(cat $file); do
                lenword=${#word}
                if [[ $lenword -gt lenLW ]]; then
                  lenLW=$lenword
                  LongestWord=$word
                elif [[ $lenword -gt lensecLW ]]; then
                  lensecLW=$lenword
                  secLongestWord=$word
                fi

        done
done
printf "Het langste woord is: %s, met %d characters\n" "$LongestWord" "$lenLW"
printf "Het tweede langste woord is: %s, met %d characters\n" "$secLongestWord" "$lensecLW"

It's this last printf thats messing up. It outputs me: , met "length of the second longest word" characters woord is: "the second longest word". note that the word and the length of it are in fact correct, just somehow in the wrong order and with part of the sentence missing.

Can anyone tell me what's going on here?

Yunnerd
  • 15
  • 3
  • 2
    I suspect your text file is in DOS/Windows format, which confuses unix tools in a variety of ways (in this case by putting carriage returns in your `word` variable; see ["Are shell scripts sensitive to encoding and line endings?"](https://stackoverflow.com/questions/39527571)). Also, `for word in $(cat $file)` can do silly things like replacing `*` in the file with a list of filenames in the current directory; it's better to use something like `while read -r word; do ... done < <(tr -s ' \n\r' '\n')` (which'll also fix the line ending problem). – Gordon Davisson Jun 03 '23 at 19:01
  • That turns out to be the problem then I think because when I made some test text files within WSL It worked fine. Thanks! – Yunnerd Jun 03 '23 at 19:13

0 Answers0