0
0
Bash Scriptingscripting~15 mins

Character classes ([a-z], [0-9]) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Filter Filenames Using Character Classes in Bash
📖 Scenario: You have a folder with many files. Some files have names with only lowercase letters, some have numbers, and others have mixed characters. You want to find files that have only lowercase letters in their names.
🎯 Goal: Build a bash script that lists filenames containing only lowercase letters using character class [a-z].
📋 What You'll Learn
Create a list of filenames stored in a variable.
Create a pattern variable using character classes to match lowercase letters.
Use a loop and conditional to filter filenames matching the pattern.
Print the filtered filenames.
💡 Why This Matters
🌍 Real World
Filtering filenames based on character patterns helps organize files, automate backups, or process specific file groups in scripts.
💼 Career
Understanding character classes and regex matching in bash is essential for system administrators and automation engineers to write efficient scripts.
Progress0 / 4 steps
1
Create a list of filenames
Create a variable called files that contains these exact filenames separated by spaces: apple, banana123, cherry, 12345, date, fig9.
Bash Scripting
Need a hint?

Use double quotes and separate filenames with spaces inside the variable.

2
Create a pattern for lowercase letters
Create a variable called pattern and set it to the regular expression ^[a-z]+$ to match filenames with only lowercase letters.
Bash Scripting
Need a hint?

The pattern should start with ^, end with $, and use [a-z]+ to match one or more lowercase letters.

3
Filter filenames with only lowercase letters
Use a for loop with variable file to iterate over $files. Inside the loop, use an if statement with [[ $file =~ $pattern ]] to check if the filename matches the pattern. If it matches, add the filename to a variable called filtered separated by spaces.
Bash Scripting
Need a hint?

Use double square brackets and the =~ operator to match regex in bash.

4
Print the filtered filenames
Print the variable filtered to display the filenames that contain only lowercase letters.
Bash Scripting
Need a hint?

Use printf "%s\n" "$filtered" to print the filenames separated by spaces.