2

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?

7

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.

  • 1
    To avoid having to repeat the foo, you can do: \v(foo)&(^\1|\1$) (though in this case that ends up being longer to type). – Stéphane Chazelas Mar 27 '18 at 13:03
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.