在BASH中将字符串读入变量,直到遇到特定单词

3

我有一个程序会输出类似下面的内容:

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个回答

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"

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

当需要“取消引用”变量时,必须引用该变量。


2
可以在bash本身完成。
stuff=${stuff/stuff2=1*/}

0
$ eval $(sed "s/=/='/;s/ [^ ]*=.*/'/")
$ echo $stuff
一些带有空格和其他特殊字符的文本

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接