我需要比较shell中的字符串:
var1="mtu eth0"
if [ "$var1" == "mtu *" ]
then
# do something
fi
但显然“*”在Shell中不起作用。有办法吗?
答案 0 :(得分:18)
使用Unix工具。程序cut
将愉快地缩短字符串。
if [ "$(echo $var1 | cut -c 4)" = "mtu " ];
......应该做你想做的事。
答案 1 :(得分:12)
bash
最短的修复:
if [[ "$var1" = "mtu "* ]]
Bash的[[ ]]
没有得到全局扩展,不像[ ]
(由于历史原因,必须这样)。
bash --posix
哦,我的发帖太快了。 Bourne shell,而不是Bash ...
if [ "${var1:0:4}" == "mtu " ]
${var1:0:4}
表示$var1
的前四个字符。
/bin/sh
${var1:0:4}
。你需要像mstrobl的解决方案。
if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]
答案 2 :(得分:6)
您可以调用expr
以匹配Bourne Shell脚本中正则表达式的字符串。以下似乎有效:
#!/bin/sh
var1="mtu eth0"
if [ "`expr \"$var1\" : \"mtu .*\"`" != "0" ];then
echo "match"
fi
答案 3 :(得分:3)
我会做以下事情:
# 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
答案 4 :(得分:2)
在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
答案 5 :(得分:1)
我喜欢使用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
这也有效,但有一些限制,例如文件不能超过几兆字节而且shell根本看不到空值,所以如果一个文件充满空值而另一个没有,(并且没有其他任何东西),这个测试看不出两者之间的任何差异。
我不使用文件比较作为一个严肃的例子,只是一个例子,说明case语句如何能够进行比test或expr或其他类似shell表达式更灵活的字符串匹配。
答案 6 :(得分:0)
或者,作为 =〜运算符的示例:
if [[ "$var1" =~ "mtu *" ]]