Single command taking two strings to extract string between them, like ‘tr’ (without expressions)

quotingsedtext processing

Saw here a way to use sed to get text between two other strings in a line, like:

sed 's/.*starting_text\(.*\)ending_text.*/\1/'

but I'd like a simple command (like tr, but for string extraction) that just took two strings and would trim everything before the first string or after the second string, e.g.

grep something some_file | between message\"\:\" " with"

and would handle escaping characters.

Best Answer

If the delimiters may appear several times per lines, you could use perl instead like:

between() {
  perl -Tlne 'BEGIN{$b=shift;$e=shift}
             print for /\Q$b\E(.*?)\Q$e\E/g' "$@"
}

And then for example:

$ echo "[b]test[e] foo [b]bar[e]" | between '[b]' '[e]'
test
bar

You can also use it as:

between BEG END file1 file2...
Related Question