annotate 1-Ruby/day2-grep.rb @ 23:720e9201dd98

Add basic grep
author IBBoard <dev@ibboard.co.uk>
date Sun, 08 Jan 2017 20:29:18 +0000
parents
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
23
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
1 #! /usr/bin/env ruby
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
2
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
3 if ARGV.length != 2
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
4 abort("Incorrect arguments - pass a single file and a pattern")
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
5 elsif not File.exist? (ARGV[0])
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
6 abort ("File #{ARGV[0]} did not exist")
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
7 end
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
8
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
9 file = ARGV[0]
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
10 pattern = Regexp.new(ARGV[1])
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
11 i = 0
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
12 File.open(file, "r").each_line do |line|
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
13 i+= 1
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
14 if line =~ pattern then
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
15 puts "#{i} #{line}"
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
16 end
720e9201dd98 Add basic grep
IBBoard <dev@ibboard.co.uk>
parents:
diff changeset
17 end