0

I have a config.py file with parameters defined as

class A:
   path='/a/b/c'
   ...

class B:
   path='/d/e/f'
   ...

I am trying to modify parameter path in class A in config.py using sed -i from a Bash script:

sed -i <script to replace path value with /x/y/z/ in class A> config.py

expected result:

class A:
    path= '/x/y/z'
    ...

class B:
    path= '/d/e/f'
    ...

I worked out how to print the value of path variable using this:

sed -i '/A/,/path/p' config.py

How can I replace the value though?

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97
media_maker
  • 53
  • 1
  • 3
  • What's your actual question? The apparent but perhaps superficial problem is that you can't use shell variables inside single quotes. – tripleee Apr 30 '19 at 06:11
  • @tripleee: I am new to shell scripting may be I am wrong. can you please let me know the solution of problem in correct way? – media_maker Apr 30 '19 at 06:19
  • If I understood what you are asking, I could try, but you need to explain what your actual question is. – tripleee Apr 30 '19 at 06:20
  • problem is I need to replace path value to '/x/y/z' from '/a/b/c' under class A which is written in a file – media_maker Apr 30 '19 at 06:21
  • 1
    For the record, I posted a meta question to get this more broadly reviewed; https://meta.stackoverflow.com/questions/384487/should-this-previously-unclear-but-improved-question-be-reopened – tripleee May 02 '19 at 08:04
  • 4
    In this particular case it may be better to use a real Python parser instead of sed, unless you can be absolutely sure that the file will be extremely simple. – user202729 May 02 '19 at 09:08
  • The question is not a duplicate of that one @Cerbrus. Completely different answer. – Alex Harvey May 02 '19 at 09:11

1 Answers1

-2

This sed solution solves your problem:1

sed -i "
  /class A/,/path/ {
    s!path=.*!path='/x/y/z'!
  }
  " config.py

Or if you want it all on one line:

sed -i "/class A/,/path/{s!path=.*!path='/x/y/z'!}" config.py

Further explanation:

  • I search within the range /class A/,/path/ and then within that range call the s/// substitution.

  • Note use of ! as an alternate delimiter in the s/// command.

1 Tested using GNU sed on Mac OS X.

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97