How do I search for pattern that is not at the beginning of a line?


Name1 Name2 Name3 Name4 Name5 Name6

Something like:


Obviously the second ^ symbol does not mean beginning of line inside []. Is there any symbol that means "not at the beginning of line"?

  • 1
    If it is just searching, include a character before the target pattern: /.Name. – muru Apr 30 '16 at 12:05
  • unfortunately this is for search and replace :( – Banavara Apr 30 '16 at 12:09
  • 4
    Then you can probably use groups: s/\(.\)Name./\1replacement/. So that you match the character and retain it in the replacement. – muru Apr 30 '16 at 12:10
  • This works perfectly for me. Thank you muru. – Banavara Apr 30 '16 at 12:55

In original vi, and in tools with POSIX BRE or ERE, there's no way to look for strings not at the beginning of the line. However, in all of these, you can use regex groups to match any character before your actual target pattern, and then keep it unchanged in the replacement.

In general, when you want to insert something between two strings, you use groups, like so:

s/\(pattern1\)\(pattern2\)/\1 foo \2/

Correspondingly, to match something not at the beginning of the line, it will be the second pattern, and a . will be the first. And for patterns not at the end of the line, it will be the first, and a . the second:


You could use a negative lookbehind:


\( \) Are special matching parentheses

^ Is beginning of line, of course

\@<! is a negative lookbehind. Essentially, if it finds what's in the parentheses, it excludes it from the match.

See :h \@<! for more information.

  • 2
    I'm pretty sure the original vi doesn't support lookarounds. – muru Apr 30 '16 at 15:56
  • Oh, fair enough. I'm not as familiar with original vi, but I thought that all the regex still worked. Good to know that it doesn't all carry over. – Tumbler41 May 2 '16 at 14:53
  • 1
    You can check the help. For example, :h /\@<! - they will be marked {not in Vi}. – muru May 2 '16 at 15:10

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.