Friday, February 26, 2010

Re: vi, search string and comment line howto?

> Hello, I can't figure out the syntax to search for a certain string and then
> comment out that line. I know you can have multiple commands on a single
> line, but I can't figure it out. As an example I have a "file" with the
> following contents:
>
> line 1 and stuff
> line 2 contains my_string
> line 2 and stuff
>
> Now I want to vi the "file" and comment out the line containing "my_string"
> by running the following commands:
> vi file #to start editing "file"
> /my_string #to search for the line I want to comment, containing
> "my_string"
> I# #to append a comment (#) to the beginning of the
> current line
> :wq #to write and quit
>
> I should be able to string all the above commands together separated by a
> pipe:
> vi -c "/my_string | I# | :wq" file

You're passing command-line (Ex) commands to vim, not normal-mode
commands, so you can do this using ex commands instead:

vi -c "/my_string/s/^/#/" -c "wq" file.txt

Or, if you want to comment all instances of it:

vi -c "g/my_string/s/^/#/" -c "wq" file.txt

or even just do it in sed:

sed -iBAK '/my_string/s/^/#/' file.txt

-tim

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment