Awk or grep question

I have this data file

[abc]
def
ghi
[jkl]
[mno]

From this file; I can run grep and easily get all the lines that have "[" in them. How can I get the contents of the text inside "[]".

For instance:

abc
jkl
mno

thank

+3
source share
4 answers
sed -n 's/\[\(.*\)\]/\1/p' file

Explanation: -n suppresses the printing of each line in STDOUT, but /pat the end of the regular expression it activates this behavior again, as a result of which all the corresponding lines will be printed. The regular expression itself matches everything between the brackets and replaces the entire string with it.

+2
source

Try:

sed -n 's/\[\([^]]*\)\]/\1/p'

or

awk -F "[][]" '$2 != "" {print $2}'

or

grep -Po '(?<=\[)[^]]*(?=])'
+3
source

grep "\ [" | sed -e 's/\ [//' -e 's/\]//'

0

, awk

$ cat file
[abc]
def [ xxx]
ghi
[jkl]
[mno]
[zz
zzzz]


$ awk 'BEGIN{RS="]";FS="["}/\[/{print $NF }' file
abc
 xxx
jkl
mno
zz
zzzz

Ruby (1.9 +)

 ruby -0777 -ne 'puts $_.scan(/\[(.*?)\]/m)' file

Or you can only do this with a shell

$ var=$(<file)
$ IFS="]"
$ set -- $var
$ for i in $@; do echo ${i##*[}; done
0
source

Source: https://habr.com/ru/post/1792986/


All Articles