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 :(
CodePudding user response:
Using sed 's/PATTERN/REPLACEMENT/', here is my proposed modified command:
sed -i 's#\(BASE_DIR = os.path.expanduser("\)~/.teststring/\(")\)#\1/tmp.teststring/\2#' test.py.NEW
- uses the
's///'command. - in
s///, the/character can be replaced by another one, to avoid confusion. Like in this particular case, you process files and paths, so I like to use#instead of/for thes///separator. Hences###.
PATTERN: \(BASE_DIR = os.path.expanduser("\)~/.teststring/\(")\). It is divided in 3 sections:
- 1)
\(BASE_DIR = os.path.expanduser("\). This part does not change so I enclosed it in\(\)to reuse it later. Parenthesis that are not part of the pattern must be "backslashed". - 2)
~/.teststring/. This part will change, it is the part of the line that you want matched from the original file. - 3)
\(")\): closing double-quote and parenthesis, this does not change. Enclosed in\(\)to reuse it later.
REPLACEMENT: \1\/tmp.teststring/\2.
- i)
\1is the first part I "saved" for later reuse in no1) above. - ii)
/tmp.teststring/the new text to replace the text from no2) above. - iii)
\2is the second part I "saved" for later reuse in no3) above.
One detail I could not understand, your test.py file uses path "~/.teststring/", yet you tried to match it with "~/.paddleocr/". I guess that was a mistake?
CodePudding user response:
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
