How do I use the "^" and "$" symbols with regular expressions in a bash script? Please give me an example using both symbols.
^ 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
$ 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
As muru pointed out in the comments
$ don't match first and last lines in regular expressions, although that may be true in other platforms/programs.