Skip to content

Instantly share code, notes, and snippets.

@weirdbricks
Created September 16, 2014 23:00
Show Gist options
  • Save weirdbricks/783c3b84ecdc2c7ea962 to your computer and use it in GitHub Desktop.
Save weirdbricks/783c3b84ecdc2c7ea962 to your computer and use it in GitHub Desktop.
cat replacement in ruby
#!/usr/bin/ruby
#by Lampros Chaidas
#cat replacement in ruby - if the -n switch is provided the lines start with a number
#check if the -n option is given to prepend each line with a line number
if ARGV.include? "-n"
@lines=true
ARGV.delete("-n")
end
#checks if the file exists and returns true/false
def file_exists? (filename)
File.exist?(filename)
end
#line counter - we set it outside the loop so it doesn't reset to 0 for every file we add
@i = 0
def print_file (filename)
#using the foreach here so we don't read the entire file in memory, instead we go line-by-line
File.foreach(filename) do |line|
@i = @i + 1
#prepends line with the line number
if @lines==true then line = " #{@i} #{line}" end
#puts a space in front of numbers less than 0 to make output even
if @i < 10 then line.sub!("#{@i}"," #{@i}") end
puts "#{line}"
end
end
#loops through the files in the ARGV list
ARGV.each do |item|
#if the file doesn't exist, skip
next if file_exists?(item)==false
#print the contents of the file
print_file item
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment