0
0
Bash Scriptingscripting~5 mins

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

Choose your learning style9 modes available
Introduction

Character classes help you match groups of characters easily. They save time when you want to find letters or numbers in text.

You want to find all lowercase letters in a file.
You need to check if a string contains only digits.
You want to filter lines that have letters or numbers.
You want to replace all digits with another character.
You want to validate input to allow only certain characters.
Syntax
Bash Scripting
grep '[a-z]' filename

# or

grep '[0-9]' filename

Use square brackets [] to define a range of characters.

[a-z] means any lowercase letter from a to z.

[0-9] means any digit from 0 to 9.

Examples
This prints each lowercase letter on its own line.
Bash Scripting
echo "hello123" | grep -o '[a-z]'
This prints each digit on its own line.
Bash Scripting
echo "hello123" | grep -o '[0-9]'
This prints all letters, uppercase and lowercase.
Bash Scripting
echo "Test123" | grep -o '[A-Za-z]'
Sample Program

This script shows how to find letters and digits separately in a text string.

Bash Scripting
#!/bin/bash

text="User123 logged in at 10am"

echo "Letters found:"
echo "$text" | grep -o '[a-z]'

echo "Digits found:"
echo "$text" | grep -o '[0-9]'
OutputSuccess
Important Notes

Character classes are case sensitive. Use [A-Z] for uppercase letters.

Use -o option in grep to print each match on a new line.

Ranges must be in order, like a-z or 0-9, not z-a.

Summary

Character classes let you match groups of characters easily.

[a-z] matches lowercase letters, [0-9] matches digits.

Use them with grep or other tools to find or filter text.