How to remove all lines in a file containing a variable, only when located on a line somewhere between braces in BASH?

I am trying to remove all of the matches of $word from a file, but only on lines where $word is placed somewhere within { and } which also appear on the same line, e.g.:

{The cat liked} the fish.
The mouse {did not like} the cat.
The {cat did not} like the spider.

If $word is set to "cat", then lines 1 and 3 are deleted, because "cat" appears between the { and }. If $word is set to "like", then lines 1 and 2 are deleted, because this search term appears on those lines between the { and }. Line 3 is not deleted, because like appears outside of the braces.

  • The braces are never nested.
  • The braces never appear split across lines.

I have tried various things, but these all returned errors:

sed -i "/\{*$word*\}/d" ./file.txt

sed -i "/\{.*$word.*\}/d" ./file.txt

sed -i "/\{(.*)$word(.*)\}/d" ./file.txt

How can I remove all of the lines in a file containing a variable, but only when the found variable was on a line and found between two braces?


sed -i "/{.*$word.*}/d" ./file.txt

\{ in sed actually have a special meaning, not the literal {, you should just write a { to represent the literal character. (which would be confusing if you are well familiar with perl regex ...)


Be careful with -i, if this is in a script, and accidently $word is not defined or set to empty string, this command will delete all lines containing { no matter what between }.

I would take the answer that @cybeliak gave a little further. If you really want to match cat and not, say scat, then you need to delimit your expression with word boundaries:

sed '/{.*[[:<:]]'$word'[[:>:]].*}/d'

Note - I prefer to use ' ' style quotes to prevent any unintended side-effects...

As an aside, I am a big fan of not using the -i flag. Pipe the result into a different file and confirm for yourself that it's good, before deleting the original.

Much easier to do with awk:

awk -v s="cat" -F '[{}]' '!($2 ~ s)' file
The mouse {did not like} the cat.

awk -v s="like" -F '[{}]' '!($2 ~ s)' file
The {cat did not} like the spider.

Need Your Help

Rails link_to :format => :xlsx not generating link to .xlsx path

ruby-on-rails ruby ruby-on-rails-3

If I hit this url: http://localhost:3000/reports/action.xlsx it shows a generated xlsx file.

Reindenting HTML with Embeded Ruby Code (erb)

html ruby textmate indentation

I'm wondering if there's an existent solution to the following problem:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.