Friday, April 15, 2022

[SOLVED] sed replace line by escaping special chars

Issue

I am trying to replace lines using sed, and usually this works fine, but I am now encountering a string which does not seem to play ball with sed :(

file: test.py

$ cat test.py
BASE_DIR = os.path.expanduser("~/.teststring/")

I replace this line using:

sed -i '/BASE_DIR = os.path.expanduser("~/.paddleocr/")/c\BASE_DIR = os.path.expanduser("/tmp/.teststring/")' test.py

I get:

sed: -e expression #1, char 35: unknown command: `.'

Not sure what is causing this. I tried escaping the . using \. but this does not help either :(


Solution

I think your first " should be a '

Also, you need to escape the \ which aren't part of the sed syntax e.g.:

sed -i '/BASE_DIR = os.path.expanduser("~\/.paddleocr\/")/c\\BASE_DIR = os.path.expanduser("\/tmp\/.teststring/")' test.py


Answered By - otocan
Answer Checked By - Willingham (WPSolving Volunteer)