1

Possible Duplicate:
Replace while keeping certain “words” in vi/vim

Let's say I have several lines like

            $adv_id;
            $am_name; 
            $campaign_ids;
            $repeat_on;
            $opt_days;
            $opt_time;
            $am_or_pm;

Let's say I use visual mode to select all the lines.. how can I add characters at the start and the end of each line so it looks something like

        $_REQUEST($adv_id);
        $_REQUEST($am_name; 
        $_REQUEST($campaign_ids);
        $_REQUEST($repeat_on;
        $_REQUEST($opt_days);
        $_REQUEST($opt_time);
        $_REQUEST($am_or_pm);
Community
  • 1
  • 1
CodeCrack
  • 4,663
  • 11
  • 37
  • 68
  • 1
    See [this answer](http://stackoverflow.com/a/1174350/637284) – halex Oct 11 '12 at 18:04
  • 1
    You may find my answer [here](http://stackoverflow.com/questions/11624166/replace-while-keeping-certain-words-in-vi-vim/11624201#11624201) helpful. – Conner Oct 11 '12 at 18:52

2 Answers2

4

Pretty similar to your other question, so the explanation there should help you to understand this substitute. With the lines selected as a visual block, use this substitute command:

:'<,'>s/\$\(.*\);/$_REQUEST(\1);

As before, the '<,'> will be auto-filled for you in the command-line if you have a visual selection.

The difference here is that we're using \(\) to make a capturing group, which will capture part of the regex, and use it again in the replacement, using \1, which refers to the first capturing group.

Also, since this regex uses $ literally to position the replacement, it needs to be escaped: \$, since it has a special meaning in the regex: end of line.

If you'll need to have multiple replacements on a single line, you'll need to add the g flag, and you may want to remove the semicolon:

:'<,'>s/\$\(.*\);/$_REQUEST(\1)/g

The reverse regex, e.g. replacing $_REQUEST($adv_id); with $adv_id;, is pretty similar:

:'<,'>s/\$_REQUEST(\(.*\))/\1

Here we capture everything between the parens in a $_REQUEST(...); in a capturing group, and that capturing group is the entire replacement.

Community
  • 1
  • 1
pb2q
  • 54,061
  • 17
  • 135
  • 139
1

In visual mode, hit : and use this in the command line:

:'<,'>s/^\(.*\);$/$_REQUEST(\1);/g

The \( and \) capture the matched expression for the line and the \1 recalls the captured group in the substitution.

Using the :'<,'> tells Vim to filter the current selection through the following command (which is s in this case).

jheddings
  • 24,331
  • 7
  • 47
  • 62