Home > OS >  How can I replace a string containing special characters?
How can I replace a string containing special characters?

Time:07-27

I have a text file that contains a line with brackets, character, integers, and : symbols.

I want to replace [0:1] with [2:4]

$ cat input.txt
str(tr.dx)[0:1]

Expected output:

str(tr.dx)[2:4]

I tried

sed -i 's/str(tr.dx)[0:1]/str(tr.dx)[2:4]/g' input.txt

but it does not work. How can I fix this?

CodePudding user response:

You may use this sed:

sed 's/\(str(tr\.dx)\)\[0:1]/\1[2:4]/' file

str(tr.dx)[2:4]

Here:

  • \(str(tr\.dx)\) matches str(tr.dx) and captures it in group #1
  • We need to escape the dot in regex
  • \[0:1] matches [0:1]. Here we need to escape [
  • \1 is back-reference for capture group #1
  • Related