We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Ruby - delimiter problem

philsivyer
philsivyer asked
on
Medium Priority
468 Views
Last Modified: 2012-08-13
Hello
Trying to change the delimiters in attached file to comma - I should end up with 15 columns seperated by commas.
so far my script is as follows.

f = File.open("C:/RUBY_WORKING_MODELS/data_by_column_access.txt", "r")
lines = f.readlines
lines.each do|line|
line = line.gsub(/(DATA)/,'').gsub(/\" "/,',') 
puts "#{line}"
end

Open in new window

data-by-column-access.txt
Comment
Watch Question

Looks like you're escaping the first quote in gsub when you don't have to.


line.gsub(/(DATA)/,'').gsub(/\" "/,',') 
 
# should be
 
line.gsub(/(DATA)/,'').gsub(/" "/,',') # without escaping slash

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
You'll also have to get rid of the very first and very last quote, since they won't match /" "/, which you can do after you put the commas in.

Author

Commented:
Hello
Still not working as expected - I had a similar problem a while ago where Gertone offered a solution with a different outcome. The script below may give some clues as to the delimiter problem. If you remove row one (headers) from the attached file and run the following script you will see that each record has been delimited correctly - unfortunately, the output is top down i.e. one row for each field.
What I need in this case is row by row with the fileds delimited correctly.
The script.
line = File.open("C:/RUBY_WORKING_MODELS/ears_data_by_column.txt").readlines
line.each do|line|
line = line.gsub(/(DATA)/,'')
line = line.gsub('\"', 'DOUBLEQUOTE')
line = line.gsub(/'\"'/,',').gsub('\r\n', ' ').gsub(/\s+/, ' ')
line = line.scan(/(("[^"]*")|(\d+))/) do |full,a,b|
full = full.inspect.gsub('DOUBLEQUOTE', '\"').gsub(/\\/,'').gsub(/\""/,'"')
puts "#{full}"
end
end

Author

Commented:
Hello
Just wondering if any more thoughts on this problem.
Whoops, I missed your previous comment.

I'll check it out later today if no-one else gets to helping you first.

Author

Commented:
Thanks
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.