?

Log in

Bob wonders how many word per he writes on average... - unixish [entries|archive|friends|userinfo]
Unixish - Solving problems the UNIX way

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Bob wonders how many word per he writes on average... [Nov. 23rd, 2006|02:31 pm]
Unixish - Solving problems the UNIX way
unixish
[yaarg]
Problem 4:

Bob has been doing a lot of writing recently (plain text files that he stores in ~/doc) and he's simply curious about how many words per line he writes on average. He's stumped how to work this out using only the standard UNIX tools though...

Can you help him once again?
LinkReply

Comments:
(Deleted comment)
[User Picture]From: scimon
2006-11-23 03:11 pm (UTC)

Re: Awk ..?!

Sigh. Scimon resort to perl for doing the maths bit.

perl -le ' ( $_, $l, $w ) = split m!\s+!, `cat ~/doc/* | wc -lw`; print $w > 0?$l / $w:0'
(Reply) (Parent) (Thread)
[User Picture]From: tjernobyl
2006-11-23 05:48 pm (UTC)
First attempt:
cat ~/doc/* | wc | xargs perl -e 'print $ARGV[1]/$ARGV[0]."\n"'

Pure-shell implementation in a bit. bc and dc seem awfully obtuse.
(Reply) (Thread)
[User Picture]From: tjernobyl
2006-11-23 06:49 pm (UTC)
cat ~/doc/* | wc -lw | xargs --replace dc -e '2 k {} r / p'


The breakdown:

cat ~/doc/*

Dumps all files in ~/doc

wc -lw

Count the number of lines and words

xargs --replace

Whatever gets piped in, use as parameter for the following program. replace {}
with parameter.

dc -e '2 k {} r / p'

Set precision to 2 decimal places. Push the incoming number of lines and words
on the stack. Reverse the position of the top two items on the stack. Divide
the top two numbers on the stack by each other. Print the result.

4 characters less. Whee!
(Reply) (Parent) (Thread)
(Deleted comment)
From: yaarg
2006-11-24 11:20 am (UTC)
indeed!
(Reply) (Parent) (Thread)