2013-04-27 47 views
2

我有一个程序,输出是这样的:读串入一个变量,直到在BASH某个词

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 

,但我得到的是“东西=一些”过来,再次。

回答

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" 
+0

非常感谢!这工作完美。 – NStorm 2013-04-27 02:20:03

0
$ eval $(sed "s/=/='/;s/ [^ ]*=.*/'/") 
 
$ echo $stuff 
Some text with spaces and other $pecial characters 
1

你可以用简单的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 

这是至关重要的引用变量时,你需要 “解引用” 了。

1

可以在bash来完成自身

stuff=${stuff/stuff2=1*/}