Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read string into a variable until a certain word in BASH

Tags:

bash

macos

I have a program that outputs something like this:

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

I am trying to get all of that string up until stuff2=1 in a variable, so the variable would be:

stuff=Some text with spaces and other $special characters

I have tried this:

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

but all I get is "stuff=Some" over and over again.

like image 544
NStorm Avatar asked Feb 15 '26 19:02

NStorm


1 Answers

How about this?

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"
like image 165
sehrope Avatar answered Feb 18 '26 12:02

sehrope



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!