-2
      - ../logs/nginx:/var/log/nginx
    env_file:
      - ../env/uid.env

should be converted to

      - ../logs/nginx:/var/log/nginx
    env_file:
      - ../env/nginx.env
      - ../env/uid.env

There are multiple occurences of "env_file" in the file, which is why I need to match the line above as well. I'm struggling with the newline. I've tried

awk '/    env_file:/{print;print "      - ../env/nginx.env";next}1' filename

this worked but it doesn't include the line above. Then I've tried this and it didn't work.

awk '/nginx\n    env_file:/{print;print "      - ../env/nginx.env";next}1' filename

EDIT: To clarify my issue. I cannot use the first attempt due to multiple occurrences of "env_file" in my file. I need to match an additional line (the line containing "nginx") above. And that's what I am struggling with.

Lavair
  • 888
  • 10
  • 21
  • I've tested your first attempt on the input you provided with gawk 5.0.0 and it worked as you describe it should. I cannot understand what your issue is. Could you please elaborate? PS: you can remove whitespaces in the regex comparison, I think `/env_file/` – Daemon Painter Mar 17 '20 at 14:36
  • From what I could understand, the OP wants to match a block of two lines, the first line containing `nginx` and the second line `envfile:`. I think he should [edit] the question to make that clear. – Quasímodo Mar 17 '20 at 14:41
  • Does this answer your question? [Can awk patterns match multiple lines?](https://stackoverflow.com/questions/14350856/can-awk-patterns-match-multiple-lines) – Daemon Painter Mar 17 '20 at 14:47
  • @Quasímodo, yes, now that I read the question under that light it makes much more sense. Although, I do believe it is duplicated question then. – Daemon Painter Mar 17 '20 at 14:48

1 Answers1

2

If you want to match a block of two lines, you can use a "flag" variable that is set whenever the first line of the block gets matched.

awk '
  1
  /nginx/{flag=1;next}
  flag==1 && /    env_file:/{flag=0;print "      - ../env/nginx.env"}
  flag=0
' filename
Quasímodo
  • 3,812
  • 14
  • 25