I would like to put "assert " before every line of the form expression1==expression2 in my code. How do I do it with the vim substitute command? Thanks!
Edit: How to put "assert" only to lines that contains "==" but does not begin by "if"?
CodePudding user response:
You can do the following:
:g/==/s/^/assert /
:g
: apply globally/==/
: select all lines that match the pattern==
s/…/…/
: replace:^
: match the beginning of the line …assert
: … and replace it withassert
.
Do note that this is of course performing a purely textual search and replace. As such, it will also put assert
in front of commented or string-quoted occurrences of ==
.
If you want to exclude lines that start with a pattern, such as if
, this gets quite a bit harder. But you can use a negative lookbehind:
:g/\(^if.*\)\@<!==/s/^/assert /
\(^if.*\)\@<!
basically means: match the subsequent pattern only if the line does not start with if
.
CodePudding user response:
To expand on @konrad-rudolph's answer, the last part of a :g
command can be any Ex command, including :g
.
This means that, just like in your shell, you could "chain" commands instead of spending too much time crafting elaborate patterns.
In your shell, you could do the following to print out every line with a ==
but no leading if
:
$ grep == filename | grep -v if
Where you search for the lines with ==
, then search through the results for lines without leading if
.
In Vim, you could do the following to prepend assert
to every line with a ==
but no leading if
:
:g/==/v/^if/s/^/assert /
Where :g/==/
marks every line with ==
, v/^if/
marks those of those lines without leading if
(simplified), and s/^/assert /
prepends only those lines with assert
.
See :help :g
and :help :v
and scroll down a little to find a recursive example.