Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep substring between two delimiters

I have a lot of bash scripts that use perl expressions within grep in order to extract a substring between two delimiters. Example:

echo BeginMiddleEnd | grep -oP '(?<=Begin).*(?=End)'

The problem is, when I ported these scripts to a platform running busybox, 'integrated' grep does not recognize -P switch. Is there a clean way to do this using grep and regular expressions?

Edit: There is no perl, sed or awk on that platform. It's a lightweight linux.

like image 275
Ulrik Avatar asked Oct 13 '14 19:10

Ulrik


2 Answers

Assuming there's no more than one occurrence per line, you can use

sed -nr 's/.*Begin(.*)End.*/\1/p'

With grep and non-greedy quantifier you could also print more than one per line.

like image 172
Vytenis Bivainis Avatar answered Nov 10 '22 04:11

Vytenis Bivainis


Use bash built-in parameter substitution:

# grab some string from grep output
f=BeginMiddleEnd
middleend=${f/Begin/}    # do some substitution to lose "Begin"

echo $middleend
MiddleEnd

beginmiddle=${f%%End}    # strip from right end to lose "End"
echo $beginmiddle
BeginMiddle

Loads more examples here.

like image 42
Mark Setchell Avatar answered Nov 10 '22 04:11

Mark Setchell