我需要比较shell中的字符串:

var1="mtu eth0"

if [ "$var1" == "mtu *" ]
then
    # do something
fi

但显然“*”在Shell中不起作用。有办法吗?

有帮助吗?

解决方案

<代码>的bash

最短的修复:

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

Bash的 [[]] 不会得到全局扩展,不像 [] (由于历史原因,它必须这样)。


bash --posix

哦,我的发帖太快了。 Bourne shell,而不是Bash ...

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

$ {var1:0:4} 表示 $ var1 的前四个字符。


<代码> / bin / sh的

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

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

其他提示

使用Unix工具。程序 cut 将很乐意缩短字符串。

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

......应该做你想做的事。

您可以调用 expr 来匹配Bourne Shell脚本中正则表达式的字符串。以下似乎有效:

#!/bin/sh

var1="mtu eth0"

if [ "`expr \"$var1\" : \"mtu .*\"`" != "0" ];then
  echo "match"
fi

我会做以下事情:

# 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}<*>quot;` -eq 1 ] ; then

我喜欢使用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表达式更灵活的字符串匹配。

或者,作为 =〜运算符的示例:

if [[ "$var1" =~ "mtu *" ]]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top