开发者

Awk or grep question

开发者 https://www.devze.com 2023-02-11 14:57 出处:网络
I have this datafile [abc] def ghi [jkl] [mno] From this file; i c开发者_如何学JAVAan run grep and easily get all lines that have \"[\" in them. How can I get the contents of text inside \"[]\".

I have this datafile

[abc]
def
ghi
[jkl]
[mno]

From this file; i c开发者_如何学JAVAan 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


Give this a try:

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

or

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

or

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


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号