检查变量是否匹配,如果找不到差异
我有2个变量的数据。
var1='abc;mno;def'
var2='mno;xyz'
** var2 can also be 'def;mno;abc'
我想比较var1和var2
if [[ $var1=$var2 ]]
then
echo "MATCHED"
else
echo "Not Matched"
fi
这将为我提供基本验证,但我的要求有些不同。我想要var1中存在的数据,但在var2中缺少数据,也存在var2中存在的数据,但在var1中缺少我,
我希望以下格式的数据:
abc;mno;def,mno;xyz,Not Matched,abc;def(## data present in var1 but missing in var2),xyz(data present in var2 but missing in var1)
第二种情况 var1 ='abc; mno; def' var2 ='def; mno; abc'
输出
abc;mno;def,def;mno;abc,Matched, ,
任何建议都很棒。
I have data in 2 variables.
var1='abc;mno;def'
var2='mno;xyz'
** var2 can also be 'def;mno;abc'
I want to compare var1 and var2
if [[ $var1=$var2 ]]
then
echo "MATCHED"
else
echo "Not Matched"
fi
This would give me basic validation but my requirement is bit different. I want data present in var1 but missing in var2 and also data present in var2 but missing in var1
I want data in below format :
abc;mno;def,mno;xyz,Not Matched,abc;def(## data present in var1 but missing in var2),xyz(data present in var2 but missing in var1)
Second case
var1='abc;mno;def'
var2='def;mno;abc'
Output
abc;mno;def,def;mno;abc,Matched, ,
Any suggestion would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您使用的是
bash
,请尝试以下操作:输出:
第二种情况的输出:
tr ';' '\n' <<< “$var1” | sort
将$var1
分成已排序的行要提供给
comm
的数据。与$var2
相同。comm <(...) <(...)
比较两个输入,然后将数据排序为三列取决于数据的唯一性。
comm
输出的字段分隔符)被替换与
;
一起使用read
命令进行正确处理。否则读取
将跳过前导字段分隔符。
var1
独有)累积在数组
col1
。与col2
和col3
相同。$var1
和$var2
是否匹配数组
col1
和col2
。如果两者都为空,则变量匹配。这是一个 awk 替代方案,仅供参考:
Assuming you are using
bash
, would you please try the following:Output:
Output for the second case:
tr ';' '\n' <<< "$var1" | sort
breaks$var1
into lines of sorteddata to feed to
comm
. Same with$var2
.comm <(...) <(...)
compares the two inputs then sorts the data intothree columns depending on the uniqueness of the data.
comm
output, are replacedwith
;
to be properly handled withread
command. Otherwiseread
will skip leading field separators.
var1
) are accumulated in thearray
col1
. Same withcol2
andcol3
.$var1
and$var2
by examining the lengthof arrays
col1
andcol2
. If both are empty, the variables match.Here is an
awk
alternative just for reference: