0
0
Bash Scriptingscripting~15 mins

Capture groups in Bash in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Capture groups in Bash
📖 Scenario: You work in a small IT team that manages server logs. You want to extract specific parts of log entries to analyze them quickly.
🎯 Goal: Build a Bash script that uses capture groups with regular expressions to extract the date and error message from a log entry.
📋 What You'll Learn
Create a variable with a sample log entry string
Create a regular expression pattern with capture groups for date and error message
Use Bash's regex matching to extract the date and error message
Print the extracted date and error message
💡 Why This Matters
🌍 Real World
Extracting parts of log files helps IT teams quickly analyze errors and events.
💼 Career
Many system administrators and DevOps engineers use Bash scripts with regex to automate log analysis.
Progress0 / 4 steps
1
Create a log entry variable
Create a variable called log_entry and set it to the string "2024-06-15 ERROR Disk space is low".
Bash Scripting
Need a hint?

Use double quotes to assign the string to log_entry.

2
Create a regex pattern with capture groups
Create a variable called pattern and set it to the regex string '([0-9]{4}-[0-9]{2}-[0-9]{2}) ERROR (.+)' which captures the date and error message.
Bash Scripting
Need a hint?

The pattern uses parentheses to capture the date and the error message separately.

3
Use regex matching to extract capture groups
Use an if statement with [[ $log_entry =~ $pattern ]] to match the pattern. Inside the if, assign date=${BASH_REMATCH[1]} and error_msg=${BASH_REMATCH[2]} to get the captured groups.
Bash Scripting
Need a hint?

Use BASH_REMATCH array to access capture groups after matching.

4
Print the extracted date and error message
Use echo to print the date and error_msg variables on separate lines.
Bash Scripting
Need a hint?

Use two echo commands to print each variable on its own line.