4

I use the following code to delete a line :

sed -i "0,/$DELETE_THIS/{/$DELETE_THIS/d;}" file.txt

But this code fails if the variable DELETE_THIS contains special characters, like ., /, * and so on...

Is there a way to tell sed to ignore all special characters and use them as basic text ?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
bob dylan
  • 1,862

1 Answers1

6
  • You have a string in $DELETE_THIS, which you want to pass to sed in such a way that sed will treat it literally.

  • For this, you must quote all characters which are meaningful to sed.

  • Put a backslash before them. For example, using Bash syntax:

    DELETE_THIS="$(<<< "$DELETE_THIS" sed -e 's`[][\\/.*^$]`\\&`g')"
    
  • This will convert, for example, ^ab[c-d]\ef$ into \^ab\[c-d\]\\ef\$.

AlexP
  • 10,455