Reputation: 35
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
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
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
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
Reputation: 113844
$ 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
$ echo "$tester_one" | awk '{sub(/.*set /,""); sub(/ where.*/,""); print;}'
abc=7
If your grep supports the -P
(perl-like) option:
$ echo "$tester_one" | grep -oP '(?<=set ).*(?= where)'
abc=7
Upvotes: 5
Reputation: 34145
You can get it out with sed. Something like:
echo "$tester_one" | sed 's/.* set \(.*\) where .*/\1/'
Upvotes: 1