0

I'm writing a bash script which will isolate a portion of a string and save it to a variable in a bash script. Assuming $INSTALL_INFO is a variable with the file I wish to pull data from, I'm doing something like this.

 BOOST=`cat $INSTALL_INFO | grep 'BOOST:' | sed 's/BOOST://g' | sed 's/^[ \t]*//'`

In this case, boost is the keyword I'm looking for. The format for the items in the file is:

<possible whitespace><exact title><indeterminate whitespace><data I want><possible whitespace>

there has got to be a cleaner way of doing this with one sed command, but I was unable to figure anything out.

  • It would help to see some exact input lines and some exact expected output lines. – mwp May 15 '18 at 19:16
1

The way to approach this is to use sed -n, which will only print lines that match the expression(s), and one expression that describes the entire line, keeping only the parts you want.

BOOST=$(sed -n 's/^.*BOOST:[ \t]*\([^ \t]*\).*$/\1/p' $INSTALL_INFO)

The trailing /p tells sed to print the line (after the replacement has been performed).

If your "data I want" can itself contain whitespace, it gets a bit trickier. You have to modify the expression to "chew up" the whitespace at the end of the line. I would switch to Perl to be able to use its "reluctant" modifier (a ? after a repetition operator):

BOOST=$(perl -ne 'print if s/^.*BOOST:\s*(.*?)\s*$/\1/' install_info.txt)

Of course, with Perl you can just print the part that matches instead of modifying the line:

BOOST=$(perl -ne 'print $1 if /BOOST:\s*(.*?)\s*$/' install_info.txt)
  • note that the OP had a grep that limited the input for sed... – Jeff Schaller May 15 '18 at 19:25
  • @JeffSchaller Yup, an unnecessary one. – mwp May 15 '18 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.