Created
January 23, 2009 10:27
-
-
Save Farzy/50965 to your computer and use it in GitHub Desktop.
Ruby for system administration
This file contains 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
# Small example of the use of Ruby for system administration | |
# This sample script does the following: | |
# - Read a text file, "data.in". This is our main data | |
# - Read a list of data patterns, one per line. Each line is just a word or a sentence. | |
# - Suppress each line of the input file that contains one of the patterns | |
# - Output to "data.out" | |
# Version 1: simple syntax without blocks. But the opened files have to be | |
# closed manually if necessary. | |
# Read file as an array of lines | |
data_in = File.readlines("data.in") | |
# Same thing, but strip newlines | |
rej = File.readlines("content-to-delete.txt").map { |l| l.strip } | |
# Build a simple regular expression | |
rejreg = Regexp.new(rej.join("|")) | |
# And output the result without the rejected lines | |
data_out = open("data.out", "w") | |
data_out.puts(data_in.reject { |l| rejreg.match(l) }) | |
data_out.close | |
# Version 2: Feel the power of Ruby blocks | |
# No leftover open file descriptors or local variables | |
# have been hurt in this version. | |
File.open("data.in") do |infile| | |
# Build a simple regular expression. I left this one on two lines | |
# instead of writing an obscure one-liner.. | |
rej = File.readlines("content-to-delete.txt").map { |line| line.strip } | |
rejreg = Regexp.new(rej.join("|")) | |
File.open("data.out", "w") do |outfile| | |
outfile.puts(infile.readlines.reject { |line| rejreg.match(line) }) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment