How do I use the "^" and "$" symbols with regular expressions in a bash script? Please give me an example using both symbols.
1 Answer
^
matches the beginning of a string. For example:
echo "A string with A" | grep ^A
matches only strings that start with A
. Notice how the second A is not matched as it is not at the beginning of the string.
echo "Some string with A" | grep ^A
^A
doesn't match anything because the string does not start with A
.
Likewise $
matches the end of a string:
echo "A good string" | grep g$
g$
matches only the g at the end of the string.
echo "A string in which g is not the end" | grep g$
returns nothing because it does not end in g
.
As muru pointed out in the comments ^
and $
don't match first and last lines in regular expressions, although that may be true in other platforms/programs.
-
Thank you for the explanation and trusting me! This is a simple and short explanation, but easy to understand! Apr 20, 2015 at 1:26
-
Also the caret is used to negate a character class; for example
c[^a]t
will match "cut" but not "cat"– kosJun 9, 2015 at 13:44
a="hello"; b="bye"; [[ $a =~ ^h ]] && echo $a starts with hello; [[ $b =~ e$ ]] && echo $b ends with e;
- what problem do you have, exactly?