0
0
Bash Scriptingscripting~5 mins

Quantifiers (*, +, ?) in Bash Scripting

Choose your learning style9 modes available
Introduction
Quantifiers help you find patterns in text by telling how many times a part can repeat. They make searching easier and smarter.
You want to find lines with zero or more spaces between words.
You need to check if a word appears one or more times in a file.
You want to match optional characters in a filename pattern.
You are filtering logs and want to find entries with or without a certain tag.
Syntax
Bash Scripting
pattern*
pattern+
pattern?
* means 'zero or more' of the pattern before it.
+ means 'one or more' of the pattern before it.
? means 'zero or one' of the pattern before it.
Examples
Find lines with zero or more 'a's (matches everything because zero is allowed).
Bash Scripting
grep 'a*' file.txt
Find lines with one or more 'a's using Perl regex (-P).
Bash Scripting
grep -P 'a+' file.txt
Find 'color' or 'colour' because 'u' is optional.
Bash Scripting
grep -E 'colou?r' file.txt
Sample Program
This script creates a file with color words. It then uses quantifiers to find lines matching patterns with zero or more 'u's, one or more 'o's, and optional 'u'.
Bash Scripting
#!/bin/bash
# Create a sample file
echo -e "color\ncolour\ncolr" > colors.txt

# Find lines with zero or more 'u's after 'colo'
grep 'colou*r' colors.txt

# Find lines with one or more 'o's
grep -P 'o+' colors.txt

# Find lines where 'u' is optional
grep -E 'colou?r' colors.txt
OutputSuccess
Important Notes
In basic grep, '+' and '?' may not work without -E or -P options.
Use 'grep -E' for extended regex where + and ? work without escaping.
'*' always works in basic grep as zero or more.
Summary
* means match zero or more times.
+ means match one or more times (needs -E or -P in grep).
? means match zero or one time (needs -E or -P in grep).