0

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...

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • I'm assuming you named `time` as an example -- it's a little more complicated than most, if not. See [BashFAQ #32](http://mywiki.wooledge.org/BashFAQ/032) for details, and if you want a question specifically about capturing its output, that should actually be in the title. – Charles Duffy Jan 05 '16 at 15:51
  • 1
    ...for a working example (tested against ksh AJM 93u+ 2012-08-01) with `time` as the command at issue: `( time true ) 2>&1 | awk '/real|sys/ { print }'` – Charles Duffy Jan 05 '16 at 15:54
  • ...to explain why this is so interesting, by the way -- `time` is a keyword in ksh and bash; it's not a regular command, or even a regular builtin. This allows it to take a pipeline as an argument rather than only a simple command, as a regular builtin would be limited to doing. – Charles Duffy Jan 05 '16 at 15:57
  • If the linked question doesn't help, could you edit your question to be more representative of what you're really trying to accomplish? – Charles Duffy Jan 05 '16 at 16:10
  • Much better. That said, "gather the information" doesn't say much -- do you a shell variable per value? And a fully correct one-liner will be be much less readable than a more verbose solution; why do you specify such? – Charles Duffy Jan 05 '16 at 16:32

1 Answers1

1

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]}"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441