Click to See Complete Forum and Search --> : shell script question


JamesD
04-16-2003, 06:58 AM
Hi,

I've been working on several shell scripts for a class that I am following, and I am really stuck on one of the questions. I was wondering if somebody could point me in the right direction as to how to solve this problem. (note: i dont need the whole solution, just a few pointers)

This is the problem:

Write a script that will generate a list containing the words from the file words.dutch.small, including the amount of bytes that each woord consists of. The list should be sorted by the amount of bytes each word is made up of.

Hint: Look at the manual page of wc
Hint: Use command substitution in some way

Note: the words.dutch.small file has one word per line and is sorted alphabetically.

The problem I am stuck on for now is that i cant get wc to work on a single word. If i pass it a word it thinks it is a filename. And we arent allowed to make files in our shell scripts.

mrBen
04-16-2003, 07:09 AM
OK - I'm not going to give you the answer, because that would be cheating ;)

BUT

Think of it this way - you know what wc can do, and you know that you're supposed to use command substitution, so what command could you substitute in place of the file in wc that would acheive your goal.

Oh, and a loop might prove helpful too.

HTH

JamesD
04-16-2003, 07:22 AM
hi

The code I am playing around with at the moment is the following:

for i in `cat words.dutch.small`
do
$bytes=`wc -c < $i`
echo $bytes, $i
done

but then it gives me a huge list saying WORD: Cant open, where WORD is a word from the file. I could put $i in a file and then do wc - c < filename on it, but that isnt allowed :(

The little plan as to how to solve this problem was to use command substitution to put all the $bytes, $i into a list, and then use sort -n on it to sort it numerically by the amount of bytes. But i cant get wc to work the way i want it (because i am doing something wrong probably)

JamesD
04-16-2003, 08:04 AM
Hmmm i'm still stuck on this :(

Maybe you could just give me the solution, or part of it, and I'll see how you did it and learn from there.

hotleadpdx
04-16-2003, 09:38 AM
JamesD -

Read the man page on wc - pay attention to "without a filename, wc counts standard input."

A hint as to what you're doing wrong -


$bytes=`wc -c < $i`


You're redirecting input into wc -c which will be treated as a filename redirection with wc (see the man page regarding where wc looks for a filename).

You're 90% there, you just have to switch your thinking around a bit. :)

chrism01
04-16-2003, 11:41 AM
thats the line alright, just re-cast it a bit as per the hint given.
:)

JamesD
04-16-2003, 11:54 AM
$bytes=`wc -c < $i`

should be

$bytes=`echo $i | wc -c`

Finally figured it out, thx a lot all of you :)

chrism01
04-16-2003, 06:59 PM
Now you know why we couldn't give anymore clues without giving the answer ;)
Bet you'll remember that trick for looong time :)