我需要比较shell中的字符串:
var1="mtu eth0"
if [ "$var1" == "mtu *" ]
then
# do something
fi
但很明显,"*"在壳牌不起作用。有办法做到吗?
使用Unix工具。程序cut
将愉快地缩短字符串。
if [ "$(echo $var1 | cut -c 4)" = "mtu " ];
应该做你想做的事。
bash
最短修复:
if [[ "$var1" = "mtu "* ]]
Bash的[[ ]]
没有得到glob扩展,这与[ ]
不同(由于历史原因,必须进行扩展)。
bash --posix
哦,我发得太快了。Bourne shell,而不是Bash。。。
if [ "${var1:0:4}" == "mtu " ]
${var1:0:4}
表示$var1
的前四个字符。
/bin/sh
啊,对不起。Bash的POSIX仿真还不够深入;真正的Bourne原始shell没有CCD_ 9。你需要一些类似mstrobl的解决方案。
if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]
您可以调用expr
来将字符串与Bourne Shell脚本中的正则表达式进行匹配。以下似乎有效:
#!/bin/sh
var1="mtu eth0"
if [ "`expr "$var1" : "mtu .*"`" != "0" ];then
echo "match"
fi
我喜欢使用case语句来比较字符串。
就是一个微不足道的例子
case "$input"
in
"$variable1") echo "matched the first value"
;;
"$variable2") echo "matched the second value"
;;
*[a-z]*) echo "input has letters"
;;
'') echo "input is null!"
;;
*[0-9]*) echo "matched numbers (but I don't have letters, otherwise the letter test would have been hit first!)"
;;
*) echo "Some wacky stuff in the input!"
esac
我做过类似的疯狂事情
case "$(cat file)"
in
"$(cat other_file)") echo "file and other_file are the same"
;;
*) echo "file and other_file are different"
esac
这也很有效,但有一些限制,比如文件不能超过几兆字节,外壳根本看不到null,所以如果一个文件充满了null,而另一个没有(也没有其他任何东西),那么这个测试将不会看到两者之间的任何区别。
我不使用文件比较作为一个严肃的例子,只是一个例子,说明case语句如何能够进行比test、expr或其他类似shell表达式更灵活的字符串匹配。
我会做以下操作:
# Removes anything but first word from "var1"
if [ "${var1%% *}" = "mtu" ] ; then ... fi
或者:
# Tries to remove the first word if it is "mtu", checks if we removed anything
if [ "${var1#mtu }" != "$var1" ] ; then ... fi
在Bourne shell中,如果我想检查一个字符串是否包含另一个字符串:
if [ `echo ${String} | grep -c ${Substr} ` -eq 1 ] ; then
用两个`
倒勾号封装echo ${String} | grep -c ${Substr}
:
检查子字符串是在开头还是结尾:
if [ `echo ${String} | grep -c "^${Substr}"` -eq 1 ] ; then
...
if [ `echo ${String} | grep -c "${Substr}$"` -eq 1 ] ; then
或者,作为=~运算符的一个例子:
if [[ "$var1" =~ "mtu *" ]]