superloopnetworks
superloopnetworks

Reputation: 514

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

Upvotes: 0

Views: 255

Answers (3)

Alan Gómez
Alan Gómez

Reputation: 378

A regex based solution is:

:%s/\(\(^.*\n\)\{8}\)/\1  serial_num: xxxxx\r/g

Where ^.*\n match a single whole line till the return character \n, then \{8} repeats the selection 8 times, \(...\) encapsulate the final group.

Upvotes: 0

Enlico
Enlico

Reputation: 28416

With GNU Sed

sed '/type: /a\  serial_num: xxxxx' your_file

Upvotes: 2

romainl
romainl

Reputation: 196566

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

Upvotes: 2

Related Questions