Bash: How to store a specific line of CLI output into a file?

These types of thing are not generic in nature, but specific though approach is generic


I am assuming, you want to replace OpenConnect.Cookie = line with OpenConnect.Cookie = BLABLABLABLABLA

So, to first create required string , you can use

sed -i  "s/^OpenConnect.Cookie =.*$/$( command_giving_output  | grep 'COOKIE=' | sed "s/COOKIE='//; s/'//g; s/^/OpenConnect.Cookie = /")/" external_filename

Here I am using command substitution to first create required string

command_giving_output  | grep 'COOKIE=' | sed "s/COOKIE='//; s/'//g; s/^/OpenConnect.Cookie = /"

and then substituting required line by this required string

sed -i  "s/^OpenConnect.Cookie =.*$/output from above command substitution /" external_filename

You can read the cookie using a combination of bash's read and grep:

IFS="'" read -r _ cookie _ < <(some-command | grep '^COOKIE')

This uses process substitution to feed the output of some-command | grep '^COOKIE') to read. With IFS="='", we split the input on ', discarding the first element of the split (COOKIE=) (and any remaining text after the closing quote), while saving the second in the cookie variable.

Then we can use sed to replace the text:

sed -i 's/>>>INSERT CONTENT OF THE COOKIE HERE<<</'"$cookie"'/' some-file

This depends on the cookie text not containing special characters like &, though.


You could use:

. <(command | grep "^COOKIE=")
sed -i "s/\(OpenConnect.Cookie\)\s*=.*/\1 = ""$COOKIE""/" file

Where:

  • file is the existing file with contents as described in the question.
  • command is the your command that prints the text to the terminal.
  • grep "^COOKIE=" searches for a line starting with COOKIE=
  • and the dot in the beginning of the command "sources" the output. This means that the output is interpreted as shell code. Thus the variable $COOKIE is set in the current shell.
  • The sed command then replaces the line in the destination file with the contents of the variable $COOKIE.