0
0
Bash Scriptingscripting~5 mins

Capture groups in Bash in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a capture group in Bash regular expressions?
A capture group is a part of a regular expression enclosed in parentheses. It saves the matched text so you can use it later in your script.
Click to reveal answer
beginner
How do you access the text matched by a capture group in Bash?
You can access the matched text using the special array variable BASH_REMATCH. BASH_REMATCH[0] is the full match, BASH_REMATCH[1] is the first capture group, and so on.
Click to reveal answer
beginner
Example: What does this Bash code print?
[[ "hello123" =~ ([a-z]+)([0-9]+) ]]
echo "${BASH_REMATCH[1]}"
echo "${BASH_REMATCH[2]}"
It prints: hello 123 The first capture group ([a-z]+) matches 'hello', the second ([0-9]+) matches '123'.
Click to reveal answer
beginner
Why use capture groups in Bash scripts?
Capture groups let you extract parts of a string easily. For example, you can get a username from an email or a number from a filename without complicated commands.
Click to reveal answer
beginner
What command structure is needed to use capture groups in Bash?
You use the double square brackets [[ ]] with the =~ operator to test a string against a regex with capture groups. Example:
[[ "$string" =~ regex ]]
Click to reveal answer
In Bash, which variable holds the text matched by capture groups after a regex test?
AMATCH_GROUPS
BBASH_REMATCH
CREGEX_CAPTURE
DGROUP_MATCH
What does BASH_REMATCH[0] contain after a regex match?
AThe first capture group
BThe regex pattern
CThe entire matched string
DThe last capture group
Which operator is used inside [[ ]] to test a regex with capture groups in Bash?
A=~
B==
C!=
D=>
How do you write a capture group in a Bash regex?
A[ ]
B{ }
C< >
D( )
What will happen if you try to access BASH_REMATCH before a successful regex match?
AIt will be empty or unset
BIt will contain the previous match
CIt will cause an error
DIt will contain the regex pattern
Explain how to use capture groups in Bash to extract parts of a string.
Think about how you test a string and then get parts of it.
You got /4 concepts.
    Describe a simple real-life example where capture groups in Bash can help automate a task.
    Imagine you want to get just a piece of text from a bigger string.
    You got /4 concepts.