Noobie
Noobie

Reputation: 35

Extract data based on exact match of a string stored in a variable

So I was trying to extract data from a variable,

var="hi hello HI high" # --> This is the input

The pattern I wish to extract is kept in,

var2="hi" #  --> this is the pattern to be matched

If my input is the variable var1, then it should extract only the pattern in var2.

The output should technically have only:

hi

It should not pick up the other string which are partially matching the pattern:

hi HI high

I tried using:

echo $var|sed "s/.*\($var2\).*/\1/p"

and:

echo $var|grep "^$var2$"

It didn't work for me.

Also could you please suggest solutions that follow the POSIX standard as I need to implement this idea in Solaris and Linux.

Upvotes: 0

Views: 484

Answers (2)

anubhava
anubhava

Reputation: 784918

If I am interpreting the question right, you probably want this:

var2="hi"
re='\b(hi)\b'

var="hi hello HI=really"
[[ $var =~ $re ]] && echo "${BASH_REMATCH[1]}" || echo "no match"
hi

var="hi hello HI=really"
[[ $var =~ $re ]] && echo "${BASH_REMATCH[1]}" || echo "no match"
no match
  • =~ is used for regex matching in bash
  • ${BASH_REMATCH[1]} represents captured group #1
  • \b is used for word boundary (use [[:<:]] and [[:>:]] on OSX)

Using sed:

sed "s/.*\<\($var2\)\>.*/\1/" <<< "$var"
hi

Using grep:

grep -oE "$re" <<< "$var"
hi

Upvotes: 2

karakfa
karakfa

Reputation: 67467

Let's build up step by step

> echo "hi hello HI=really" | grep -o "hi"
hi

create a variable for the search pattern

> var2="hi"; echo "hi hello HI=really" | grep -o "$var2"
hi

create another variable for the source text

var2="hi"; var="hi hello HI=really"; echo "$var" | grep -o "$var2"
hi

I'm not sure of the practical value though. Perhaps if you can state your original problem you'll get more useful help.

Upvotes: 1

Related Questions