0
0
Bash Scriptingscripting~5 mins

Capture groups in Bash in Bash Scripting

Choose your learning style9 modes available
Introduction
Capture groups let you find and save parts of text that match a pattern. This helps you work with specific pieces of text easily.
Extract a username from an email address.
Get the date parts (year, month, day) from a filename.
Find and save phone number parts from a text.
Split a string into parts based on a pattern.
Check if a string matches a pattern and get details.
Syntax
Bash Scripting
if [[ string =~ regex ]]; then
  echo "${BASH_REMATCH[1]}"
fi
Use double square brackets [[ ]] with =~ to match regex.
Captured groups are saved in BASH_REMATCH array starting at index 1.
Examples
This splits 'hello123' into letters and numbers using capture groups.
Bash Scripting
text="hello123"
if [[ $text =~ ([a-z]+)([0-9]+) ]]; then
  echo "Letters: ${BASH_REMATCH[1]}"
  echo "Numbers: ${BASH_REMATCH[2]}"
fi
Extracts username and domain from an email address.
Bash Scripting
email="user@example.com"
if [[ $email =~ ([^@]+)@(.+) ]]; then
  echo "User: ${BASH_REMATCH[1]}"
  echo "Domain: ${BASH_REMATCH[2]}"
fi
Sample Program
This script extracts year, month, and day from a filename using capture groups.
Bash Scripting
#!/bin/bash

input="2024-06-15_report.txt"

if [[ $input =~ ([0-9]{4})-([0-9]{2})-([0-9]{2})_report\.txt ]]; then
  year=${BASH_REMATCH[1]}
  month=${BASH_REMATCH[2]}
  day=${BASH_REMATCH[3]}
  echo "Year: $year"
  echo "Month: $month"
  echo "Day: $day"
else
  echo "No match found."
fi
OutputSuccess
Important Notes
BASH_REMATCH[0] contains the full matched string.
Capture groups start from index 1 in BASH_REMATCH.
Make sure to quote variables when using regex to avoid word splitting.
Summary
Capture groups save parts of matched text for easy use.
Use [[ string =~ regex ]] and BASH_REMATCH array in Bash.
Index 1 and up in BASH_REMATCH hold the captured groups.