Thiago Saba Santos
Thiago Saba Santos

Reputation: 3

Extracting multiple variables from a shell command in one line

I need to get some lines that a command returns to me. New example:

$ Return_Data
HOSTNAME:xpto.com.br 
IP:255.255.255.0 
DISKSPACE:1TB 
LOCATION:argentina 

I need only the LOCATION and IP lines and I need to gather that information in one single line. How should I proceed? I can use awk, shell, ksh, etc...

Upvotes: 0

Views: 42

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295619

The cleanest solution is not, natively, a one-liner.

typeset -A data                   # Create an associative array.
while IFS=: read -r key value; do # Iterate over records, splitting at first :
  data[$key]=$value               # ...and assign each to that map
done < <(Return_Data)             # ...with your command as input.

# ...and, to use the extracted values:
echo "Hostname is ${data[HOSTNAME]}; location is ${data[LOCATION]}"

That said, you can -- of course -- put all these lines together with ;s between them:

# extract content
typeset -A data; while IFS=: read -r key value; do data[$key]=$value; done < <(Return_Data)

# demonstrate its use
echo "Hostname is ${data[HOSTNAME]}; location is ${data[LOCATION]}"

Upvotes: 1

Related Questions