0
0
Bash Scriptingscripting~10 mins

Character classes ([a-z], [0-9]) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Character classes ([a-z], [0-9])
Start
Input string
Apply regex with character class
Match characters in class?
Yes No
Extract/Use
Output matched chars
The script reads a string, applies a regex with character classes to find matching characters, then outputs those matches.
Execution Sample
Bash Scripting
input="abc123XYZ"
matches=$(echo "$input" | grep -o '[a-z]')
echo "$matches"
Extracts and prints all lowercase letters from the input string.
Execution Table
StepInput StringRegex UsedMatch FoundOutput
1abc123XYZ[a-z]aa
2abc123XYZ[a-z]ba b
3abc123XYZ[a-z]ca b c
4abc123XYZ[a-z]No more matchesa b c
💡 No more lowercase letters to match, grep stops.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
input"abc123XYZ""abc123XYZ""abc123XYZ""abc123XYZ""abc123XYZ"
matches""aa\nba\nb\nca\nb\nc
Key Moments - 2 Insights
Why does grep -o '[a-z]' output each letter on a new line?
Because grep -o prints each match separately on its own line, as shown in execution_table rows 1-3.
What happens if the input has uppercase letters when using '[a-z]'?
Uppercase letters do not match '[a-z]', so they are ignored, as seen in the input 'abc123XYZ' where only lowercase letters are output.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after step 2?
Aa\nc
Ba\nb
Cb\nc
Da\nb\nc
💡 Hint
Check the Output column in execution_table row 2.
At which step does grep stop finding matches?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look for 'No more matches' in the Match Found column.
If the regex changes to '[0-9]', what would be the first match found?
Aa
BX
C1
DNo match
💡 Hint
Check the input string and look for digits in variable_tracker.
Concept Snapshot
Character classes in bash regex match sets of characters.
[a-z] matches any lowercase letter.
[0-9] matches any digit.
Used with grep -o to extract matches.
Each match prints on a new line.
Uppercase letters or other chars do not match these classes.
Full Transcript
This example shows how to use character classes like [a-z] in bash scripting with grep. The input string 'abc123XYZ' is processed by grep -o '[a-z]' which finds each lowercase letter separately. Each match is printed on its own line, so the output is 'a', then 'b', then 'c'. Uppercase letters and digits are ignored because they don't match the class. The execution table traces each step of matching and output. The variable tracker shows how the matches variable grows with each found letter. This helps beginners see how character classes work in practice and how grep outputs matches line by line.