Noobie
Noobie

Reputation: 35

Extract part between two strings in a variable in Unix

I have a string,

tester_one="update set_tables set abc=7 where bcd=9"

Here I wish to extract only the part between "set" and "where",

abc=7

I tried a couple of Unix commands, but it picked up any occurrences of set or where encountered, before the part where I want it to pick up.

I have an idea on how to do it Java but I am lost in Unix as I am new to this.

Upvotes: 2

Views: 15372

Answers (5)

ghoti
ghoti

Reputation: 46856

As with your other question, this can be achieved in pure bash, without the use of external tools like sed/awk/grep.

#!/usr/bin/env bash

tester_one="update set_tables set abc=7 where bcd=9"

output="${tester_one#* set }"
output="${output% where }"

echo "$output"

Note the spaces around "set" and "where" in the parameter expansion lines. As you might expect, you'll need to be careful with this if the $tester_one variable contains the distinct "set" or "where" in places that you don't expect them.

That said, I like Jahid's answer better. :-)

Upvotes: 0

fedorqui
fedorqui

Reputation: 289745

You can also use set and where as field separators and print the field that lies in between them:

$ awk -F"set | where" '{print $2}' <<< "update set_tables set abc=7 where bcd=9"
abc=7

Upvotes: 1

Jahid
Jahid

Reputation: 22428

Using Bash Pattern Matching:

#!/bin/bash
tester_one="update set_tables set abc=7 where bcd=9"
pat=".* set (.*) where"
[[ $tester_one =~ $pat ]]
echo "${BASH_REMATCH[1]}"

Upvotes: 1

John1024
John1024

Reputation: 113844

Using sed

$ echo "$tester_one" | sed -E 's/.*set (.*) where.*/\1/'
abc=7

To capture it in a variable:

$ new=$(echo "$tester_one" | sed -E 's/.*set (.*) where.*/\1/')
$ echo $new
abc=7

Using awk

$ echo "$tester_one" | awk '{sub(/.*set /,""); sub(/ where.*/,""); print;}'
abc=7

Using grep -P

If your grep supports the -P (perl-like) option:

$ echo "$tester_one" | grep -oP '(?<=set ).*(?= where)'
abc=7 

Upvotes: 5

viraptor
viraptor

Reputation: 34145

You can get it out with sed. Something like:

echo "$tester_one" | sed 's/.* set \(.*\) where .*/\1/'

Upvotes: 1

Related Questions