views:

38

answers:

3

I am new to shell scripting.

I want to know is there a way in which I can get a difference of two strings or values of two variables.

There are two variables:

value1 = "alok"  
value2 = "kumar alok"

so I want to get a result as

result = value1~value2

my expected result is

result="kumar"

is there any way I can do it?

can someone help me or give me some suggestions in the way it can be done...

Thanks

Alok.Kr.

+1  A: 

probably you need to have a look at this

Vijay Sarathi
+1  A: 

As Lasse V.Karlsen says, it depends a lot on exactly what you want to get in different circumstances, but you could try the following:

result=`comm -3 <(for i in $value1; do echo $i; done | sort) \
                <(for i in $value2; do echo $i; done | sort)`

This will give you all words that are in either value1 or value2, but not both. Change the -3 to -12 to get all words in value2 that are not in value1 (i.e. leaving out any words only in value1.)

For example:

value1="alok"
value2="kumar alok"
result=`comm -3 <(for i in $value1; do echo $i; done | sort) <(for i in $value2;  do echo $i; done | sort)`
echo $result

prints

kumar
psmears
+1  A: 

here's a simple way with awk

value1="alok"
value2="kumar alok"
awk -v v1="$value1" -v v2="$value2" 'BEGIN{
  if(length(v2) >= length(v1)){
    sub(v1,"",v2)
    print v2
  }
}'

$ ./shell.sh
kumar
ghostdog74
ThanksAlok.Kr.
Kumar Alok