-3

This question already has an answer here:

So i have all these words in a text file:

dfasdfasdf
adsgad
fghjast
hdasfh
adfhadfn

And i have to display the number of chars of the smallest word without using the 'awk' and 'sed' commands... I have tried all variants of wc but it works with the full text file and not only line per line.

Edit: I apologize for not giving more details on the subject. I am learning Shell basics and have not started programming on Linux yet. The point on this exercise that i Have is to show in the screen how many characters that the shortest word has. To this point I have only learned the commands tr, cp, cut, sort, head, tail, grep, find,wc... So I can't use awk/sed/any other command that I have learned on the internet or programming on this...

marked as duplicate by Jeff Schaller, Anthony G - justice for Monica, Archemar, RalfFriedl, muru Oct 31 '18 at 8:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    What do you mean by smallest? The shortest? Can you use sort? – choroba Oct 30 '18 at 19:55
  • Yes, the shortest one. I have used sort but it only sorts me the words by alphabetical order. – TOY Oct 30 '18 at 19:57
  • 1
    mapfile -t arr < yourtextfile; for f in "${arr[@]}"; do printf '%s\n' "${#f}"; done | sort -n |head -n1 or using the read as follows: while read -r line; do printf '%s\n' "${#line}"; done < fff | sort -n | head -n1 – Valentin Bajrami Oct 30 '18 at 20:01
  • If you've been given arbitrary restrictions by some external entity, perhaps you can explain what other methods you've been given to learn about so that we can meaningfully extend them. – Jeff Schaller Oct 30 '18 at 20:24
  • Yes, I apologize for not giving more details on the subject. I am learning Shell basics and have not started programming on Linux yet. The point on this exercise that i Have is to show in the screen how many characters that the shortest word has. To this point I have only learned the commands tr, cp, cut, sort, head, tail, grep, find,wc... So I can't use awk or programming on this... – TOY Oct 30 '18 at 20:53
3

Using parameter expansion, you can get the length of a variable contents:

${#variable}

Just read the file line by line and remember the shortest word:

while read word ; do
    : ${shortest:=$word}  # Initialize $shortest if not set.
    if [ ${#word} -lt ${#shortest} ] ; then
        shortest=$word
    fi
done < file.txt
echo "$shortest"

Not the answer you're looking for? Browse other questions tagged or ask your own question.