grep substring between two delimiters

Ulrik picture Ulrik · Oct 13, 2014 · Viewed 17k times · Source

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.

Answer

anubhava picture anubhava · Oct 13, 2014

You can use awk with custom field separator like this to get same output:

echo 'BeginMiddleEnd' | awk -F 'Begin|End' '{print $2}'
Middle