user2824889
user2824889

Reputation: 1185

How to read parts of a command output (after a certain character) into a bash variable?

So I have a command that returns an output in the following form

># command
VAR1=ABC
VAR2=DEF
VAR3=123

And I want to read VAR1 and VAR3 from that command into a shell script. So logically, I run the following two commands

># command | grep VAR1
VAR1=ABC
># command | grep VAR3
VAR3=123

How do I capture only the part that comes after the first equal sign? (So that "${VAR1}" = "ABC" and "${VAR3}" = "123"). Also of note, there could be another equal sign in the vale of either variable, so I need to keep everything after the first equal sign, including subsequent ones

Upvotes: 3

Views: 282

Answers (2)

Jahid
Jahid

Reputation: 22428

This should work:

># command | grep -oP '(?<=VAR1=).*'
ABC
># command | grep -oP '(?<=VAR3=).*'
123

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You can use awk:

command | awk -F = '/VAR1|VAR3/{print substr($0, index($0, "=")+1)}'
ABC
123

Breakup:

/VAR1|VAR3/    # searches for VAR1 OR VAR3
index($0, "=") # search for = in the record
substr         # gets the substring after first =

Upvotes: 1

Related Questions