2008-10-08 27 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