Text Processing
Grep Counts
Filtering Matching Lines
grep can count matching lines in a stream. A script can keep the search term in a variable so the same pipeline answers different questions.
Program
Play the script to count matching log lines after choosing the search pattern.
grep_counts.sh
#!/usr/bin/env bash
log=$'info boot\nwarn disk\nerror fail\ninfo done'
pattern=
matches="$(printf '%s\n' "$log" | grep -c "$pattern")"
echo "$pattern:$matches"
#!/usr/bin/env bash
log=$'info boot\nwarn disk\nerror fail\ninfo done'
pattern=
matches="$(printf '%s\n' "$log" | grep -c "$pattern")"
echo "$pattern:$matches"
#!/usr/bin/env bash
log=$'info boot\nwarn disk\nerror fail\ninfo done'
pattern=
matches="$(printf '%s\n' "$log" | grep -c "$pattern")"
echo "$pattern:$matches"
grep -c
`grep -c` prints the number of matching lines instead of the lines themselves.
quoted pattern
Quoting `$pattern` keeps the selected search text as one argument.
pipeline
`printf ... | grep ...` sends generated text directly into the filter.