Last active
August 24, 2016 11:48
-
-
Save KINGSABRI/fd4a34fe4aaaef9f9923264f7e107bf4 to your computer and use it in GitHub Desktop.
String parser for "key :value" text file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # | |
| # KING SABRI | @KINGSABRI | |
| # Usage: | |
| # ruby noawk.rb file.txt | |
| # | |
| # One-liner: | |
| # ruby -e 'h={};File.read("text.txt").split("\n").map{|l|l.split(":", 2)}.map{|k, v|k.strip!;v.strip!; h[k] ? h[k] << v : h[k] = [v]};h.each {|k, v| puts "#{k}:\t#{v.join(", ")}"}' | |
| # | |
| file = File.read(ARGV[0]).split("\n") | |
| def parser(file) | |
| hash = {} # Datastore | |
| splitter = file.map { |line| line.split(':', 2) } | |
| splitter.each do |k, v| | |
| k.strip! # leading and trailing whitespace | |
| v.strip! # leading and trailing whitespace | |
| if hash[k] # if this key exists | |
| hash[k] << v # add this value to the key's array | |
| else # if not | |
| hash[k] = [v] # create the new key and add an array contains this value | |
| end | |
| end | |
| hash # return the hash | |
| end | |
| parser(file).each {|k, v| puts "#{k}:\t#{v.join(', ')}"} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment