0

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
  • 1
    Do you really need "at every 8th line", or can we do after each `type:` line? Are you also open to Awk solutions? – Quasímodo Jan 18 '21 at 16:28
  • 1
    Yup, after 'type:' is just fine. I'm opened to awk solutions as well... Whatever that can provide the same results. Can you also show a solution for before 'type:' as well? Thank you so much! – superloopnetworks Jan 18 '21 at 17:15
  • 1
    Does this answer your question? [Add line after matching a pattern](https://stackoverflow.com/questions/48002485/add-line-after-matching-a-pattern) – Quasímodo Jan 19 '21 at 12:55

2 Answers2

2

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
romainl
  • 186,200
  • 21
  • 280
  • 313
2

With GNU Sed

sed '/type: /a\  serial_num: xxxxx' your_file
Enlico
  • 23,259
  • 6
  • 48
  • 102