Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm using this regex (?<=\[')[^,]* on a file containing the following line disk = ['OVS/sdasd/asdasd/asdasd/something.img, w']

I want that to return OVS/sdasd/asdasd/asdasd/something.img

How do I use grep to make it work?

I've tried grep -P "(?<=\[')[^,]*" but it returns the whole line.

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

Add the -o switch so that grep only returns what matches the pattern you're grepping for:

$ grep -Po "(?<=\[')[^,]*" data.txt 
OVS/sdasd/asdasd/asdasd/something.img
share|improve this answer
add comment

@slm already gave you the canonical answer. Here are a few more options:

Use awk and ' as field delimiter (assuming all lines have the same format):

$ awk -F "'" '($1~/ = /){print $2}'
OVS/sdasd/asdasd/asdasd/something.img, w    

Do the whole thing in perl:

$ perl -lne 'print $1 if /\[.(.*?).\]/' data.txt 
OVS/sdasd/asdasd/asdasd/something.img, w    

Use a simpler regex and parse the results:

$ grep "\[.*\]" data.txt | awk -F "'" '{print $2}'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep -o "\[.*\]" data.txt | perl -pe "s/[\[\]']//g"
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | sed 's/.*\[.\(.*\).\]/\1/'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | perl -pne 's/.*\[.(.*?).\].*/$1/'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | perl -lne 'print $1 if /\[.(.*?).\]/'
OVS/sdasd/asdasd/asdasd/something.img, w
share|improve this answer
add comment

You can also use sed without the lookaround assertion for greater portability (-o may not be available for your grep):

sed "s!['\(\[^,\]*\),.*\$!\1!;t;d;p" data.txt

Note the "strange" use of backslash escapes here. It's due to the fact that sed uses BREs by default (see this question).

Speaking of portability, why not just use Perl?

perl -nle "print \$1 if /\['([^,]*)/" data.txt
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.