Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove square brackets and any text inside?

Tags:

bash

sed

I have a document containing some text inside square brackets, e.g.:

The fish [ate] the bird.
[This is some] text.
Here is a number [1001] and another [1201].

I need to delete all of the information contained inside the square brack and the brakets, e.g.:

The fish  the bird.
 text.
Here is a number  and another .
  • I tried sed -r 's/\[[+]\]//g' file.txt, but this did not work.

How can I delete anything in the pattern [<anything>]?

like image 482
Village Avatar asked Dec 15 '22 08:12

Village


1 Answers

try this sed line:

sed 's/\[[^]]*\]//g' 

example:

kent$  echo "The fish [ate] the bird.
[This is some] text.
Here is a number [1001] and another [1201]."|sed 's/\[[^]]*\]//g' 
The fish  the bird.
 text.
Here is a number  and another .

explanation:

the regex is actually straightforward:

\[     #match [
[^]]*  #match any non "]" chars
\]     #match ]

so it is

match string, starting with [ then all chars but ] and ending with ]

like image 69
Kent Avatar answered Jan 31 '23 18:01

Kent