Thursday, February 3, 2022

[SOLVED] update line below or next line if the current line condition is met with awk or sed

Issue

I have a file which I want to update in place. IT contains the following text:

distributed_tracing:
   enabled: false
cross_application_tracer:
   enabled: true

I want to update distributed tracing to true. How can I update the next line if the current line contains "distributed_tracing"

Any solution using awk or sed will be helpful.

I tried the following solution but it did not work:

cat /file.yml | sed -e "s/(distributed_tracing:.*\n.*)enabled: false/enabled: true/g" > /file1.yml.new

Solution

awk to the rescue!

$ awk '/distributed_tracing/{n=NR} n&&NR==n+1{sub("false","true")}1' file > file.tmp && mv file.tmp file

note, added n&& not to match first line.



Answered By - karakfa
Answer Checked By - Marilyn (WPSolving Volunteer)