Vamshi Rapol
Vamshi Rapol

Reputation: 11

Grep and Replace a string in a particular pattern

I want to add/replace a string in a file with in a particular pattern. Please refer below

"dont_search_this"   => {
    -tag => "qwerty",
    -abc_asd => [ "q/rg/dfg.txt",],
    -dependent_fcv => ["me_lib",  "you_lib",], 
    -vlog_opts => (($ENV{ABC_PROJECT}) eq "xuv")
      ? [ "-error=AMR", "-error=GHJ", "-error=TYU", "-error=IJK", ]
      : [] ,
},

"search_this"   => {
    -tag => "qwerty",
    -abc_asd => [ "q/rg/dfg.txt",],
    -dependent_fcv => ["me_lib",  "you_lib",], 
    -vlog_opts => (($ENV{ABC_PROJECT}) eq "xuv")
      ? [ "-error=AMR", "-error=GHJ", "-error=TYU", "-error=IJK", ]
      :[],
},

In above data, I want to add string "-error=all", in the line -vlog_opts in search_this paragraph only. Modified should be as follows

"dont_search_this"   => {
    -tag => "qwerty",
    -abc_asd => [ "q/rg/dfg.txt",],
    -dependent_fcv => ["me_lib",  "you_lib",], 
    -vlog_opts => (($ENV{ABC_PROJECT}) eq "xuv")
      ? [ "-error=AMR", "-error=GHJ", "-error=TYU", "-error=IJK", ]
      :[],
},

"search_this"   => {
    -tag => "qwerty",
    -abc_asd => [ "q/rg/dfg.txt",],
    -dependent_fcv => ["me_lib",  "you_lib",], 
    -vlog_opts => (($ENV{ABC_PROJECT}) eq "xuv")
      ? [ "-error=AMR", "-error=GHJ", "-error=TYU", "-error=IJK", "-error=all" ]
      :[],
},

Please help me in this. Using perl is also fine.

Thank You very much!

Upvotes: 0

Views: 96

Answers (2)

zdim
zdim

Reputation: 66964

I can't help it but think that there's got to be a better way than editing the source code ... ?

Read the whole script file into a string and then follow the trail to identify the place to change

perl -0777 -wpe'
    s/"search_this"\s+=>\s+\{.*?\-vlog_opts\s+=>\s+[^\]]+\K/ADD_THIS/s; 
' file

(broken over lines for readability)

Notes

  • 0777 switch unsets the input record separator, so the file is "slurped" whole as one "line"

  • the /s modifier makes it so that . matches the newline as well

  • the \K makes it so that all matches up to that point are dropped (not consumed) so they don't have to be (captured and) entered in the replacement part. So we literally add ADD_THIS

  • Good information about \K is under "Lookaround Assertions" in Extended Patterns in perlre but keep in mind that it subtly differs from other lookarounds

Upvotes: 3

SpiceMan
SpiceMan

Reputation: 74

That looks like a perl data structure.

Any reason why can't just push "-error=all" into $hash{search_this}{-vlog_opts}->@*

Upvotes: 0

Related Questions