3

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

Ex:

Name1 Name2 Name3 Name4 Name5 Name6

Something like:

/[^^]Name.

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

4
  • 1
    If it is just searching, include a character before the target pattern: /.Name.
    – muru
    Apr 30, 2016 at 12:05
  • unfortunately this is for search and replace :(
    – Banavara
    Apr 30, 2016 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, 2016 at 12:10
  • This works perfectly for me. Thank you muru.
    – Banavara
    Apr 30, 2016 at 12:55

2 Answers 2

3

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:

0
2

You could use a negative lookbehind:

\(^\)\@<!Name\d

\( \) 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.

3
  • 2
    I'm pretty sure the original vi doesn't support lookarounds.
    – muru
    Apr 30, 2016 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, 2016 at 14:53
  • 1
    You can check the help. For example, :h /\@<! - they will be marked {not in Vi}.
    – muru
    May 2, 2016 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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