2008-10-08 60 views

回答

11

bash

最短修复:

if [[ "$var1" = "mtu "* ]] 

bash的[[ ]]没有得到水珠展开,不像[ ](必须,由于历史原因)。


bash --posix

哦,我贴得太快了。 Bourne shell中,不猛砸......

if [ "${var1:0:4}" == "mtu " ] 

${var1:0:4}意味着$var1前四个字符。


/bin/sh

啊,对不起。 Bash的POSIX仿真不够远;一个真正的原始Bourne壳没有${var1:0:4}。你需要像mstrobl的解决方案。

if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ] 
+0

`$ {var1:0:4}` - 您从哪里得到该语法?这绝对不是POSIX。 – 2011-09-16 06:23:04

+1

我的cut版本表示位置从1开始编号。``cut -c 1-4``或``cut -c -4``在这里返回正确的值。 – jotr 2016-01-25 22:02:04

18

使用Unix工具。程序cut将愉快地缩短字符串。

if [ "$(echo $var1 | cut -c 4)" = "mtu " ]; 

...应该做你想做的。

+1

是的,但有点沉重 – 2008-10-08 16:37:29

0

或者,正如=〜操作符的例子:

if [[ "$var1" =~ "mtu *" ]] 
6

你可以调用expr从Bourne Shell的脚本中对阵正则表达式的字符串。以下似乎工作:

#!/bin/sh 

var1="mtu eth0" 

if [ "`expr \"$var1\" : \"mtu .*\"`" != "0" ];then 
    echo "match" 
fi 
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 
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表达式更加灵活的字符串匹配的例子。

1

在Bourne shell中,如果我想查一个字符串是否包含另一个字符串:

if [ `echo ${String} | grep -c ${Substr} ` -eq 1 ] ; then 

附上echo ${String} | grep -c ${Substr}有两个`反引号:

要检查字符串是否在开头或end:

if [ `echo ${String} | grep -c "^${Substr}"` -eq 1 ] ; then 
... 
if [ `echo ${String} | grep -c "${Substr}$"` -eq 1 ] ; then