I am trying to use this command:
sed -i 's#\{test1\}#test2#' /example/myfile.txt
To replace instances of {test1}
with test2
.
I get the error:
sed: -e expression #1, char 17: Invalid preceding regular expression
Am I not escaping the curly braces correctly?
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
String h = "{hiren:}"; h=h. replaceAll(":\\}", ":\"\"}"); Otherwise, you can use String#replace with no regular expression nor escaping needed. String h = "{hiren:}"; h=h.
In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see python.org/doc/humor/…!
You aren't escaping the curly braces at all. In sed
, the default regular expressions are BREs, where \{
and \}
indicate a range expression. Since test1
isn't a range, your BRE is incorrect.
To fix it, you can either drop the backslashes (braces aren't special in BREs) or keep it the same and tell sed to use EREs (-r
flag with GNU sed, -E
flag with BSD/MacOSX sed).
sed -i 's#{test1}#test2#' /example/myfile.txt
You don't need escape {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With