Ruby script for replacing tab delimeters with commas
on Tuesday 11th March, 2008 Gabe speculated thusly…A trivial Ruby script for replacing any number of tabs in input.csv with a single comma and then writing it as output.csv.
The first version works from the command line and makes use of concatenating a file and piping it to a ruby command which then diverts the output in to a file, a one liner:
cat input.csv | ruby -pe 'gsub( /\t+/, "," )' > output.csv
This can be further enhanced by using the in-place-edit switch of the Ruby interpreter, editing the input.csv file and leaving a pristine copy with .bak extension.
ruby -i.bak -pe 'gsub( /\t+/, "," )' input.csv
The final version is what you might put in to a Ruby file. Although the input and output files are hard-coded, it would be trivial to allow them to be specified on the command line.
#!/usr/bin/env ruby # Initialise a new file object that is writable file = File.new( "output.csv", "w" ) # Open the existing tab delimited file and read each line File.open( "input.csv", "r" ).each do |line| # Perform a global substitution of tabs with commas and # put that in the new file file.puts line.gsub( /\t+/, "," ) end # Tidy up by closing the newly written output file. file.close
Tags: command line, Programming, Ruby, scripts