skip to Main Content

I need to modify a file in a Docker image. I would like to change the line 2357 of a Python module mod.py with sed, how can I do that ?

        raise ExchangeError(self.id + ' ' + errorText + '(#' + errorCode + ')')

The desired output would be:

        raise ExchangeError(self.id + '(#' + errorCode + ')')

or

        raise ExchangeError(self.id)

3

Answers


  1. You can use the following sed command to replace content on a specific line:

    sed '2357s/AAA/BBB/'
    

    Where:

    • 2357 is the target line number
    • s stands for "substitute", meaning replace a string
    • AAA is your original string, in your usecase:

    raise ExchangeError(self.id + ‘ ‘ + errorText + ‘(#’ + errorCode +
    ‘)’)

    • BBB is the desired replacement string

    You might have to play around with escaping special characters.

    Login or Signup to reply.
  2. If the line you want to edit is unique in the code, try the following.

    sed -i 's|raise ExchangeError(self.id + ' ' + errorText + '(#' + errorCode + ')') .*|raise ExchangeError(self.id + '(#' + errorCode + ')')|' mod.py

    It would search for the exact line and replace it.

    The cleaner syntax is as follows:

    sed -i 's|text_to_match .*|text_to_replace_with|' filename
    
    Login or Signup to reply.
  3. Try it with:

    sed -i "2357s/+ ' ' + errorText //" path/mod.py
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search