Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Counting words

54 views
Skip to first unread message

James

unread,
Jul 21, 2016, 2:20:44 PM7/21/16
to
Try to count the number of words (args)

printf aa bb cc | perl -nle 's/\s+/\n/g' | wc -l

Are there faster and more efficient ways?

TIA
James

Bit Twister

unread,
Jul 21, 2016, 3:00:29 PM7/21/16
to
$ printf "aa gg sss" | wc -w
3


$ echo aa gg sss | wc -w
3

Janis Papanagnou

unread,
Jul 21, 2016, 3:45:11 PM7/21/16
to
Shell only...

$ set aa bb cc
$ echo $#
3

Janis

>
> TIA
> James
>

Ed Morton

unread,
Jul 21, 2016, 4:35:55 PM7/21/16
to
Yes, every other reasonable way is faster and more efficient :-).

To add to that pot:

printf aa bb cc | awk '{print NF}'

Regards,

Ed.

Kaz Kylheku

unread,
Jul 21, 2016, 5:48:59 PM7/21/16
to
Count the args directly:

$ set -- aa bb cc
$ echo $#
3

Kaz Kylheku

unread,
Jul 21, 2016, 5:52:14 PM7/21/16
to
And, of course, make a function:

count_args()
{
echo $#
}


$ count_args aa bb cc
3

This will be done before the perl executable gets around to attaching libc.so.

Rakesh Sharma

unread,
Jul 27, 2016, 12:49:02 AM7/27/16
to
On Thursday, 21 July 2016 23:50:44 UTC+5:30, James wrote:
>
> Try to count the number of words (args)
>
> printf aa bb cc | perl -nle 's/\s+/\n/g' | wc -l
>

Note that the above as given will not produce the expected output.

... | perl -ple '$_=s/\S+/\n/g'

... | perl -pale '$_=@F'
0 new messages