0
0
Bash Scriptingscripting~10 mins

Anchors (^, $) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Anchors (^, $)
Start
Input String
Apply ^ anchor
Match start of string?
NoNo match
Yes
Apply $ anchor
Match end of string?
NoNo match
Yes
Full match found
End
Anchors ^ and $ check if a pattern matches the start or end of a string in bash regex matching.
Execution Sample
Bash Scripting
echo "hello" | grep -E '^he'
echo "hello" | grep -E 'lo$'
Check if 'hello' starts with 'he' and ends with 'lo' using anchors.
Execution Table
StepInput StringPatternAnchor UsedMatch ResultOutput
1hello^he^Matches starthello
2hellolo$$Matches endhello
3hello^lo^No match
4hellohe$$No match
💡 No more patterns to test; matching ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
Input Stringhellohellohellohellohello
Pattern^helo$^lohe$
Match ResultMatches startMatches endNo matchNo match
Outputhellohello
Key Moments - 2 Insights
Why does '^he' match 'hello' but '^lo' does not?
Because '^' means match only at the start of the string. 'hello' starts with 'he' but not with 'lo' (see execution_table rows 1 and 3).
Why does 'lo$' match 'hello' but 'he$' does not?
'$' means match only at the end of the string. 'hello' ends with 'lo' but not with 'he' (see execution_table rows 2 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when pattern '^he' is used on 'hello'?
A"hello"
B"" (empty)
C"he"
D"lo"
💡 Hint
Check row 1 in execution_table under Output column.
At which step does the pattern fail to match the input string?
AStep 1
BStep 2
CStep 3
DNo failure
💡 Hint
Look for 'No match' in Match Result column in execution_table.
If we change the pattern from '^he' to '^h', what would happen at Step 1?
ANo match
BMatches start
CMatches end
DMatches whole string
💡 Hint
'^h' still matches start of 'hello' as 'hello' starts with 'h' (see concept of ^ anchor).
Concept Snapshot
Anchors ^ and $ in bash regex check string positions.
^ matches start of string.
$ matches end of string.
Use with grep -E for pattern matching.
Example: '^he' matches strings starting with 'he'.
Example: 'lo$' matches strings ending with 'lo'.
Full Transcript
Anchors ^ and $ are special symbols in bash regex that let you check if a pattern is at the start or end of a string. The ^ anchor means the pattern must be at the very beginning. The $ anchor means the pattern must be at the very end. For example, using grep -E '^he' on the string 'hello' matches because 'hello' starts with 'he'. Using 'lo$' matches because 'hello' ends with 'lo'. If the pattern does not match at the required position, no output is returned. This helps you find exact matches at string edges.