Montag, 29. Dezember 2008

get options with getoptlong

install:

~# gem install getopt
Successfully installed getopt-1.3.7
1 gem installed
Installing ri documentation for getopt-1.3.7...
Installing RDoc documentation for getopt-1.3.7...

need: require 'getoptlong'



#!/usr/bin/ruby

require 'getoptlong'

opts = GetoptLong.new(
[ "--test", "-t", GetoptLong::REQUIRED_ARGUMENT ],
[ "--blub", "-b", GetoptLong::OPTIONAL_ARGUMENT ],
[ "--help", "-h", GetoptLong::NO_ARGUMENT ],
[ "--usage", "-u", GetoptLong::NO_ARGUMENT ],
[ "--version", "-v", GetoptLong::NO_ARGUMENT ]
)

opts.each do |opt, arg|
case opt
when "--test"
puts "we must extract :#{arg}:"
when "--blub"
puts "blub blub : #{arg} :"
when "--help"
puts "help yourself"
when "--usage"
puts "getoiptlong.rb"
puts " -t, -b, -h, -u , -v"
when "--version"
puts "version 0.01"
else
puts "upsala"
end
end

Sonntag, 28. Dezember 2008

print out file wiht numbers of line


#!/usr/bin/ruby
# put out file wiht numbers out
#

file=ARGV[0]

begin
lines=File.open(file, "r").readlines
format="%0#{lines.size.to_s.size}d"
lines.each_with_index { |l, i|
puts "#{sprintf(format, i+1)}: #{l}"
}
rescue
puts "no file??? or errors"
end

Donnerstag, 25. Dezember 2008

print out environment variables

ENV.each do |e|
p e
end

ENV: array of arrays

p: something like print or puts but better, doesn't interpolate!

ENV.each: iterate in a block each item of array ENV

do .. end: blocks

|e|: pipe, there is the block parameters


example:
["SHELL", "/bin/bash"]
["TERM", "xterm"]

Mittwoch, 24. Dezember 2008

create executable file, which extract a directory

umwandeln Inhalt eines Verzeichnisses in eine ausführbare Datei. die sich selbst in
ein Verzeichniss extrahiert

Lösung

Dienstag, 23. Dezember 2008

download a page and print out links

webseite runterladen und links ausgeben

Hilfslinks:
http://snippets.dzone.com/posts/show/788
http://www.example-code.com/ruby/rubyhttp.asp


Lösung:


1 #!/usr/bin/ruby
2
3
require 'net/http'
4
5 if ARGV.length >0
6 url=ARGV[0]
7 else
8 p " url file"
9 Process.exit
10 end
11
12 req = Net::HTTP.get_response(URI.parse(url))
13 line=req.body
14
15 lines=line.split(" ")
16
17 lines.each do |l|
18 if l.include?("href=http") or l.include?("href=\"http")
19 v1=l.split("\"")
20 if v1.length>1
21 puts v1[1]
22 else
23 puts v1[0]
24 end
25 end
26
27 end

replace word in a file

ein Replace-programm für Datei erstellen.
ein Wort durch ein anderen ersetzen

Lösung:

1 #!/usr/bin/ruby
2
3
puts "start"
4
5 if ARGV.length > 2
6 datei=ARGV[0]
7 muster=ARGV[1]
8 ersetzen=ARGV[2]
9 else
10 print "\n\tfile02.rb file muster replacetext\n\n"
11 Process.exit
12 end
13
14 puts "mustering file #{datei}"
15
16 f=File.open(datei, "r+")
17 lines = f.readlines # read into array of lines
18
lines.each do |it| # modify lines
19
it.gsub!(/#{muster}/, ersetzen)
20 end
21 f.pos = 0 # back to start
22
f.print lines # write out modified lines
23
24
f.truncate(f.pos)
25 f.close



syntax highlighted by Code2HTML, v. 0.9.1