Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex match square brackets once

Tags:

regex

awk

There is a text file with the following info:

[[parent]]

[son]

[daughter]

How to get only [son] and [daughter]?

$0 ~ /\[([a-z])*\]/        ???
like image 273
6axter82 Avatar asked Feb 10 '23 07:02

6axter82


2 Answers

Your regex is almost right. Just put the * inside the round brackets (in order to have the whole text inside the only group) and remember to use the ^ and $ delimiters (to avoid matching [[parent]]):

^\[([a-z]*)\]$
like image 191
Andrea Corbellini Avatar answered Feb 23 '23 10:02

Andrea Corbellini


Match any square bracket at beginning of line where the next character is an alphabetic.

awk '/^\[[a-z]/' file

You might want to add uppercase and/or numbers to the character class, depending on what your real requiements are. (Your examples show only lowercase, so I have assumed that's a valid generalization.)

like image 44
tripleee Avatar answered Feb 23 '23 09:02

tripleee