Home > Blockchain >  How can I do the same job I do when using wc commands without wc commands?
How can I do the same job I do when using wc commands without wc commands?

Time:12-06

Problem 2. Write a Bash script which prints a table of counters denoting the number of commands that start with each letter in the alphabet. Do this for the commands under /usr/bin. For example, under /usr/bin if there are 38 commands starting with letter a, 26 commands starting with letter b,... and 10 commands starting with letter z, then your script will print

  • a 38
  • ...
  • z 10

Call this script counter.sh. Exclude commands starting with non-alphabetical characters. Use loops and arrays to write this script.


You can see my homework in the above. Actually I can do this homework using wc -l command. like this:

for letter in {a..z}
do
echo "$letter $(ls /bin | grep "^$letter" | wc -l)"
done

But I don't want to use wc -l command due to my homework. I have been searching but I didn't find answer. How can I do this homework without wc command. Please help me. Thanks you for helping.

CodePudding user response:

With bash. Fill an array (a) with file names and output number of its elements (${#a[@]}):

shopt -s nullglob   # see: man bash
for letter in {a..z}; do a=(/usr/bin/$letter*); echo "$letter ${#a[@]}"; done

Output (e.g.):

a 125
b 43
c 115
.
.
.
x 172
y 9
z 14
  • Related