Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed find and replace with curly braces

Tags:

sed

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?

like image 910
atdev Avatar asked Feb 09 '12 05:02

atdev


People also ask

Can you use {} in Python?

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.

What is the purpose of {} squiggly braces in Java?

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.

How do you replace open curly braces in Java?

String h = "{hiren:}"; h=h. replaceAll(":\\}", ":\"\"}"); Otherwise, you can use String#replace with no regular expression nor escaping needed. String h = "{hiren:}"; h=h.

Are curly braces valid in Python?

In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see python.org/doc/humor/…!


2 Answers

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).

like image 38
Michael J. Barber Avatar answered Oct 16 '22 09:10

Michael J. Barber


sed -i 's#{test1}#test2#' /example/myfile.txt 

You don't need escape {}

like image 90
kev Avatar answered Oct 16 '22 10:10

kev