0
0
Bash Scriptingscripting~5 mins

Anchors (^, $) in Bash Scripting

Choose your learning style9 modes available
Introduction
Anchors help you find patterns only at the start or end of text. They make searches exact and clear.
Check if a line starts with a specific word in a log file.
Find lines that end with a certain file extension like .txt.
Validate if user input exactly matches a pattern from start to end.
Filter lines that begin or end with a number in a data file.
Syntax
Bash Scripting
pattern_start='^pattern'
pattern_end='pattern$'
The ^ symbol means the pattern must be at the start of the line.
The $ symbol means the pattern must be at the end of the line.
Examples
Finds lines in file.txt that start with 'Hello'.
Bash Scripting
grep '^Hello' file.txt
Finds lines in file.txt that end with 'world'.
Bash Scripting
grep 'world$' file.txt
Finds lines that are exactly 'Error' with nothing else before or after.
Bash Scripting
grep '^Error$' file.txt
Sample Program
This script creates a file with some lines. Then it uses anchors ^ and $ with grep to find lines starting with 'Hello', ending with 'world', and exactly matching 'Error'.
Bash Scripting
#!/bin/bash
# Create a sample file
echo -e "Hello world\nHello there\nGoodbye world\nError" > sample.txt

# Find lines starting with Hello
echo "Lines starting with 'Hello':"
grep '^Hello' sample.txt

# Find lines ending with world
echo "\nLines ending with 'world':"
grep 'world$' sample.txt

# Find lines exactly 'Error'
echo "\nLines exactly 'Error':"
grep '^Error$' sample.txt
OutputSuccess
Important Notes
Anchors ^ and $ work line by line in tools like grep.
If you forget anchors, grep finds the pattern anywhere in the line.
Use anchors to make your searches precise and avoid extra matches.
Summary
Use ^ to match the start of a line.
Use $ to match the end of a line.
Anchors help find exact matches in text files or input.