2

我有一个输出如下内容的程序:

stuff=Some text with spaces and other $pecial characters stuff2=1 stuff3=0

我试图在变量中获取所有字符串,直到 stuff2=1,所以变量将是:

stuff=Some text with spaces and other $special characters

我试过这个:

for word in $output
while [ $word != "stuff2=1" ]
do
   var+=" "$word
done
done

但我得到的只是一遍又一遍的“stuff=Some”。

4

4 回答 4

2

可以在 bash 本身中完成

stuff=${stuff/stuff2=1*/}
于 2013-04-27T16:48:52.393 回答
2

这个怎么样?

stuff='Some text with spaces and other $pecial characters stuff2=1 stuff3=0'

var=""
for word in $stuff
do
  if [ "$word" == "stuff2=1" ]
     then
    break
  fi
  if [ "$var" != "" ]
  then
    var="${var} "
  fi
  var="${var}${word}"
done
echo "$var"
于 2013-04-27T01:07:44.650 回答
2

您可以通过简单的 bash 参数扩展来实现这一点:

line='stuff=Some text with spaces and other $pecial characters stuff2=1 stuff3=0'
truncated=${line% stuff2=1*}
echo "$truncated"
stuff=Some text with spaces and other $pecial characters

当您需要“取消引用”它时,引用变量至关重要。

于 2013-04-27T16:04:51.890 回答
0
$ eval $(sed "s/=/='/;s/ [^ ]*=.*/'/")
$ echo $stuff
Some text with spaces and other $pecial characters
于 2013-04-27T01:25:53.850 回答