我有一个输出这样的程序:
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
但我得到的只是“东西=一些”一遍又一遍。
答案 0 :(得分: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"
答案 1 :(得分: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
当您需要“取消引用”变量时,引用变量至关重要。
答案 2 :(得分:1)
可以用bash本身完成
stuff=${stuff/stuff2=1*/}
答案 3 :(得分:0)
$ eval $(sed "s/=/='/;s/ [^ ]*=.*/'/")
$ echo $stuff Some text with spaces and other $pecial characters