0

So I have a shell command with this kind of output :

sqoop-client - 2.6.4.0-91
sqoop-server - 2.6.4.0-91
storm-slider-client - 2.6.4.0-91
tez-client - 2.6.4.0-91
zookeeper-client - 2.6.4.0-91
zookeeper-server - 2.6.4.0-91

I want to store this output (service name & service version) in an array then return all the objects.

At this moment in my code I already return some fixed values like that :

#code :

 return {
   hdp_version: Facter::Core::Execution.execute('/usr/bin/hdp-select versions | tail -1'),
   sqoop: File.exist?('/etc/sqoop'),
 }

#output :
{
  hdp_version => "2.6.4.0-91",
  sqoop => false
}

How can I store the output from the shell command in a 2D array and parse all the values to return them like the example above?

Like this (but in a loop):

obj[0][0] : obj[0][1], 
obj[1][0] : obj[1][1],
[...]

Thanks

2
  • What is the current (exact) output? Commented Jul 17, 2018 at 12:25
  • Message edited. Commented Jul 17, 2018 at 12:31

1 Answer 1

2

Considering you have such an output, you just need to iterate every line in the output, split the line by " - " and store it in the result hash:

libs = "sqoop-client - 2.6.4.0-91\n" \
"sqoop-server - 2.6.4.0-91\n" \
"storm-slider-client - 2.6.4.0-91\n" \
"tez-client - 2.6.4.0-91\n" \
"zookeeper-client - 2.6.4.0-91\n" \
"zookeeper-server - 2.6.4.0-91\n"

libs_with_versions = libs.each_line.with_object({}) do |line, result|
  lib, version = line.strip.split(" - ")
  result[lib] = version
end

puts libs_with_versions

returns:

{
   "sqoop-client" => "2.6.4.0-91",
   "sqoop-server" => "2.6.4.0-91",
   "storm-slider-client" => "2.6.4.0-91",
   "tez-client" => "2.6.4.0-91",
   "zookeeper-client" => "2.6.4.0-91",
   "zookeeper-server"=>"2.6.4.0-91"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you very much! it works. At the end I return all the values like this : return { components: libs_with_versions, hdp_version: Facter::Core::Execution.execute('/usr/bin/hdp-select versions | tail -1'), sqoop: File.exist?('/etc/sqoop'), } Could you explain me this : libs.each_line.with_object({}), especially the ({}) ? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.