I am sure this is easy, I am just missing a character or two.
I need to search for a particular term in a file, and when I find it, I need to append something to that
The :g//
command is what you're looking for — it runs a command on each line matching a pattern:
:g/Thing to find/ s/$/ Stuff to append/
As mentioned, :g//
is what you're after, but one further efficiency for your particular need is to run a normal command as part of the global. s
is just one of a bunch of commands that :g//
can take. You could also d(elete)
, j(oin)
, and pretty much whatever ex commands you can imagine.
Another useful one is norm(al)
, which can be used to execute any normal command. From the :help
on :norm(al)
: "Commands are executed like they are typed."
So you could also achieve what you want with:
:g/Thing to find/norm Astuff to append
Let's say I'm duplicating my mysql config file for my test environment. I want to append _test to every line that starts with "database=", so:
g/^database=/norm A_test
The thing to remember is that Vim will execute everything after 'norm' as if you had typed it in. So no space between the A
command and the text to be appended (or you will get an extra space in the output).
:%s/green/bright &/g
: Replace each "green" with "bright green" in the file.
&
: substitute matched string
. You can do anything you can imagine.
You can use the flag \v
so we don't have to use as many escape characters.
append the parameter --no-startup-id
after exec
or exec_always
:%s/exec\(_always\)\?/& --no-startup-id/g
simplify it:
:%s/\vexec(_always)?/& --no-startup-id/g