3

How do I use the "^" and "$" symbols with regular expressions in a bash script? Please give me an example using both symbols.

5
  • 1
    a="hello"; b="bye"; [[ $a =~ ^h ]] && echo $a starts with hello; [[ $b =~ e$ ]] && echo $b ends with e; - what problem do you have, exactly?
    – muru
    Apr 20, 2015 at 0:32
  • 3
    This sounds like homework.. Are you just copy-pasting your homework assignment? That isn't very honest. We are happy to help you with homework problems but not do them for you.
    – Seth
    Apr 20, 2015 at 0:34
  • I am new to bash so sorry for very easy question. We have started chapter on regular expressions. What I understand about "^" is that it searches at the first line and "$" searches at the last line. I just want to make sure I am correct and see how we use these with regular expressions! Apr 20, 2015 at 0:35
  • This is not a homework or assignment. I just want to understand how to use regular expression symbols! Apr 20, 2015 at 0:36
  • They anchor the expression to beginning of the string (line) and ending of the string (line), respectively. Not the first and last lines (which it may in some programs, but not as regular expression syntax).
    – muru
    Apr 20, 2015 at 0:37

1 Answer 1

4

^ 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.

2
  • 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"
    – kos
    Jun 9, 2015 at 13:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .