Line anchors

We've already briefly mentioned line anchors. With the explanations we have presented up until now, we were only able to search for words in a line; we weren't yet able to set expectations on where those words were in the line. For this, we use line anchors.

In regular expressions, the ^ (caret) character signifies the beginning of a line, and a $ (dollar) represents the end of a line. We can use these within a search pattern, for example, in the following scenarios:

  • Look for the word error, but only at the beginning of a line: ^error
  • Look for lines ending in a dot: \.$
  • Look for an empty line: ^$

The first usage, looking for something at the beginning of a line, should be pretty clear. The following example, which uses

Get Learn Linux Shell Scripting - Fundamentals of Bash 4.4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.