3 ms·
There are times when you want a quick solution with available tools, and I imagine, there are times when you need to write a portable program that is documented
by keithpeter 9y ago
There are times when you want a quick solution with available tools, and I imagine, there are times when you need to write a portable program that is documented and that can be maintained easily.
Trying to get McIlroy's pipeline to run on Debian...
keith@lavazzared:~$ cat bash.txt | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | sed ${1}q
4200 the
...I just get the most common word. Using head instead of sed gives more lines...
keith@lavazzared:~$ cat bash.txt | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | head
4200 the
1822 is
1251 to
1221 a
1147 of
869 if
804 and
570 in
567 shell
562 command
Am I holding it wrong? The source text was the bash man page.
- s_kilk 9y ago> Am I holding it wrong? Yup. The six lines are meant to be put in a script file, then invoked with the number of results to print as the first arg, where ${1} will work correctly. If you just paste it into the shell you get whatever ${1} is set to in your shell session.
- keithpeter 9y agoAll is now clear, thanks to both parent posts keith@lavazzared:~$ cat bash.txt | ./wordc.sh 10 4200 the 1822 is 1251 to 1221 a 1147 of 869 if 804 and 570 in 567 shell 562 command
- lesserknowndan 9y agoThis comment thread suggests that Knuth's approach is better, i.e., the shell script version doesn't really explain why, what, or how it is doing what it is doing. It could have been improved by being written in a literate style that explains how each UNIX command line tool is being used and why; and would have executed in exactly the same way.
- userbinator 9y agoIt was meant to be put in a shell script that takes the number of words as its first argument, hence the "${1}q".