I'm trying to write a script that counts the number of matches of some pattern in a list of files and outputs its findings. Essentially I want to call the command like this:
count-per-file.sh str_needle *.c
and get output like:
Main.c: 12
Foo.c: 1
The script:
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
# count-per-file.sh SEARCH_PATTERN GLOB_EXPR
for file in "$2"; do
count=$(grep -a "$1" "$file" | wc -l)
if [ $count -gt 0 ]; then
echo "$file: $count"
fi
done
The problem is if I call it like so I don't know how to loop over the file list, so this outputs nothing:
count-per-file.sh str_needle *.c
I found this answer but it deals the glob pattern being the only argument to the script, whereas in my script the first argument is the search pattern, and the rest are the files expanded from the glob.
As suggested I used
shift
which seems to 'pop' the first argument. Here's my working script: