0

I would like to select (in Vim) the lines that start with the same pattern. For example, if I have this:

if (...) {
    print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}

Skip to this in a quick way in Vim.

if (...) {
    if (debug == true) print "Accepted\n"
    o.attr_out = "Accepted";
}
else if (...) {
    if (debug == true) print "Partially accepted\n"
    o.attr_out = "Partially Accepted";
}
else if (...) {
    if (debug == true) print " NOT Accepted\n"
    o.attr_out = "Not Accepted";
}
romainl
  • 186,200
  • 21
  • 280
  • 313
F A Fernández
  • 101
  • 1
  • 8

1 Answers1

3

You can use the vim command:

:%s/print "/if ( debug == true ) &/g

here's a quick breakdown of the command:

% - include all lines in the search

s - substiture the 1st pattern with the 2nd.

/print "/ - the pattern you're searching for.

if ( debug == true ) &/ - the text you want to replace the pattern with (note & will put back the print " text that it found in the search).

g - replace all occurrences on the same line. (Technically you don't need that here - since there's only one occurrence of print " on each line).

Refer to the :help :s command for more information.

cguk70
  • 611
  • 3
  • 7
  • 2
    Could you add `:help ...` references? Also the `/g` is not necessary in this case. – romainl Feb 08 '22 at 11:35
  • Hi, I was aware of the replace option in Vim, but I'm afraid it doesn't fix my problem, since this will change it for all the "prints" in the file. Instead, I only want to do it for those that are between a certain number of lines (for example, between 50 and 87), without modifying the other prints that are in the file. Thanks for the help :-) – F A Fernández Feb 09 '22 at 10:23
  • Replace `%` with `50,87` and it'll only apply the search and replace to those lines. – cguk70 Feb 09 '22 at 12:15
  • 1
    @FAFernández, please don't move the goal post. You asked for "the lines" without further requirements, which makes this is a perfect answer for the question as you asked it. – romainl Feb 09 '22 at 17:07
  • @romainl it's right. I will try to be more explicit in the future. – F A Fernández Feb 11 '22 at 10:13
  • @cguk70 Thanks for the tip, it will help me a lot in the future. – F A Fernández Feb 11 '22 at 10:14