6

What command is used to search for a specific string at the beginning of line and at the end of the line in vi editor?

dr_
  • 29,602

2 Answers2

11

To search for foo at the beginning or the end of a line:

/^foo\|foo$

Edit: To avoid retyping the foo, you could also use a backreference (suggested by @StéphaneChazelas):

/\v(foo)&(^\1|\1$)

Explanation: To search for foo at the beginning of a line you use /^foo, while to search for it the end of a line you use /foo$. (Read here for more info.) The escaped "or" delimiter (|) checks for either match.

dr_
  • 29,602
7

Use / followed by the appropriate regular expression.

  • To search for a string at the start of a line, use ^string as the expression.
  • To search for a string at the end of a line, use string$ as the expression.

The ^ and $ characters anchors the expression at the start and end of the line respectively.

Kusalananda
  • 333,661