share/rbbt_commands/tsv/get in rbbt-util-5.21.91 vs share/rbbt_commands/tsv/get in rbbt-util-5.21.92

- old
+ new

@@ -1,26 +1,63 @@ #!/usr/bin/env ruby require 'rbbt-util' require 'rbbt/util/simpleopt' -options = SOPT.get("-tch--tokyocabinet:-tcb--tokyocabinet_bd") +options = SOPT.setup <<EOF -file = ARGV.shift -value = ARGV.shift +Query a TSV value +$ rbbt tsv get [options] <filename.tsv|-> <key> + +Use - to read from STDIN + +-tch--tokyocabinet File is a tokyocabinet hash database +-tcb--tokyocabinet_bd File is a tokyocabinet B database +-f--fields* Fields to extract +-k--key_field* Use this field as key +-h--help Print this help +-l--lines Separate in lines +EOF + +rbbt_usage and exit 0 if options[:help] + +file, key = ARGV + +raise ParameterException, "Please specify file and key" if key.nil? + +file = STDIN if file == '-' + case when options[:tokyocabinet] tsv = Persist.open_tokyocabinet(file, false) when options[:tokyocabinet_bd] tsv = Persist.open_tokyocabinet(file, false, nil, TokyoCabinet::BDB) else - tsv = TSV.open(file, :grep => value ) + if String === file + file = file.dup + Path.setup(File.expand_path(file)) + end + tsv = file end -res = tsv[value] +fields = options[:fields] +key_field = options[:key_field] +fields = fields.split(/[,|]/, -1) unless fields.nil? -if res.nil? - raise "RECORD NOT FOUND" -else - puts tsv[value].report +parser = TSV::Parser.new tsv, :key_field => key_field, :fields => fields +fields ||= parser.fields +TSV.traverse(parser) do |k,v| + next unless k.include? key + if fields.length == 1 + if options[:lines] + puts (Array === v ? v.flatten*"\n" : v.to_s ) + else + puts (Array === v ? v.flatten*"\t" : v.to_s ) + end + else + fields.zip(v).each do |field,v| + puts "#{Log.color :magenta, field+":"} #{v}" + end + end +end