shergill
shergill

Reputation: 3788

Awk or grep question

I have this datafile

[abc]
def
ghi
[jkl]
[mno]

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

For example:

abc
jkl
mno

Thanks

Upvotes: 3

Views: 264

Answers (4)

kurumi
kurumi

Reputation: 25599

here's how you can do it with 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 do it with just the shell

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

Upvotes: 0

yan
yan

Reputation: 20982

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

Explanation: -n suppresses the printing of each line to STDOUT, but the /p at the end of the regex re-enables this behavior causing all matching lines to be printed. The regex itself matches everything between brackets and replaces the entire line with it.

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360105

Give this a try:

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

or

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

or

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

Upvotes: 3

Luixv
Luixv

Reputation: 8710

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

Upvotes: 0

Related Questions