Search code examples
vimyamlvi

Insert new text at every X line using vi editor


I currently have a yaml file (this file is large and follows the same format below):

- created_at: 2021-01-18 15:11:44
  created_by: joe
  hostname: sfo
  ip: 1.1.1.1
  opersys: tmsh
  platform: f5
  role: lb
  type: loadbalancer
- created_at: 2021-01-18 15:11:44
  created_by: joe
  hostname: sjc
  ip: 2.2.2.2
  opersys: tmsh
  platform: f5
  role: lb
  type: loadbalancer

I want to insert a new text (serial_num: xxxxx) at every 8th line so it looks like this:

- created_at: 2021-01-18 15:11:44
  created_by: joe
  hostname: sfo
  ip: 1.1.1.1
  opersys: tmsh
  platform: f5
  role: lb
  type: loadbalancer
  serial_num: xxxxx
- created_at: 2021-01-18 15:11:44
  created_by: joe
  hostname: sjc
  ip: 2.2.2.2
  opersys: tmsh
  platform: f5
  role: lb
  type: loadbalancer
  serial_num: xxxxx

Solution

  • Pure Vim, with :help :global and :help :put:

    " after every line matching 'type:'
    :g/type:/put='  serial_num: xxxxx'
    
    " before every line matching 'type:'
    :g/type:/put!='  serial_num: xxxxx'
    

    Pure Vim, with :help :global and :help :normal:

    " after every line matching 'type:'
    :g/type:/normal oserial_num: xxxxx
    
    " before every line matching 'type:'
    :g/type:/normal Oserial_num: xxxxx