开发者

how to get Difference of two variables

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.


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


probably you need to have a look at this


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜