1

I have text file which consists of 5 columns , if i want to replace every alternate line in second column with particular string ,how can do this in vi text editor?

eg: 1 CG 54 76 76
    2 CG 45  78 78
    3 CG 48  76 89
    4 CG 49  50 52

if i want to replace 2 nd and 4 th line (2nd column) with CA how can i do this in vi text editor?

user1407199
  • 163
  • 1
  • 1
  • 9

1 Answers1

1

If you're using vim, this is a simple macro. If you're not sure if you're using vim, then in command mode, type qq and check that you see recording in the status line at the bottom. If so, then you can use this macro.

Beginning on line 1, record the macro with: qqj0wcwCA[Esc]jq

This will edit the 2nd line and leave you on the 3rd line, and now you have the macro in register q. Type 100@q to execute the command in register q 100 times.

Command details:

  • Begin on Line 1
  • qq - this begins recording a macro, you'll see recording in the status line at the bottom.
  • j - moves to the next (alternate) line.
  • 0 - moves to the beginning of the line.
  • w - jumps to the next word (2nd column)
  • cwCA - changes this word to CA.
  • Esc key - leave edit mode.
  • j - moves to the next line.
  • q - this stops recording the macro.
pb2q
  • 58,613
  • 19
  • 146
  • 147
  • How do you map and execute such a macro? (I'm sure this is something I could google) – jahroy May 22 '12 at 23:26
  • 1
    to execute the macro use the _@_ key, followed by the register containing the macro - in the above answer we've used _q_. So, **@q** will execute the macro above. Precede _@q_ with a number _N_ to execute the macro N times, e.g.: **10@q** – pb2q May 22 '12 at 23:29
  • Awesome. Thanks! (I guess you may have already typed that, sorry) – jahroy May 22 '12 at 23:32
  • 1
    also you **can** map a macro, though I've never had a good reason to do so. **:map :MyMacroName @q** for a macro in register _q_ as above. To keep such a mapped macro around, you'd need to persist the macro and the map in vimrc. See: http://stackoverflow.com/questions/2024443/saving-vim-macros – pb2q May 22 '12 at 23:36