Celebrazio Net



Contact Us

Ruby One-Liners

June, 2011

Quick Ruby. No time to explain. Just try them.


 
ruby -e 'p (1..10).map {|n| n * n * n } '

ruby -rdate -e 'p DateTime.now.cweek'  # gives the calendar week # for the current year

## separate a list 
ruby -e 'p [22, 333, 498, 55, 11,17, 99].partition { |n| n>60|}'

##  sum the list 
ruby -e 'p (1..45).inject { |sum,n| sum + n}'

## edit in place 
ruby -pi.bak -e "gsub(/1.5/,'1.6')" v*.txt

# quick math 
ruby -e 'puts (Math.sqrt(16**2/29))'

# iterate over files, parsing
ruby -ne 'puts  $_.strip if $_ =~ /sudo/' networking/*

# quick find minimum
ruby -e 'p [19, 4, 29, 312, 81, -11].min' 

#  rewrite lines, prepending line # and tab: 
ruby -pe 'print $., "\t"'  networking/file.txt

# sum total of all integers on lines in file
ruby -ane 'BEGIN{$sum=0}; $sum+=$F.reduce(0){|s,x| s+x.to_i}; END{puts $sum}' file.txt

# print how many lines contain a string
ruby -ne 'BEGIN{$t=0}; $t+=1 if ~/1/; END{puts $t}' file.txt

# print the number of fields followed by the line: 
ruby -ane 'BEGIN{$,="\t"}; print $F.size, $_'  file.txt

# print lines with more than certain number of fields
ruby -ane 'print if $F.size > 3' file.txt

# print a number of characters (like 51 a's) 
ruby -e 'puts "a"*51'

# remove whitespace, end of each line of file: 
ruby -pe 'sub /\s*$/, "\n"' file.txt

# modify all instances of string to new string in a file: 
ruby -pe 'gsub /oldt/, "newt"' file.txt 

# modify all instances of string, when line contains 3rd string: 
ruby -pe 'gsub /oldt/, "newt" if ~/chkt/' file.txt 

# print all lines, but one first 2 fields, and those 2 reversed: 
ruby -ane 'BEGIN{$,=" "; $\="\n"}; print $F[1],$F[0]'  file.txt

# switch first 2 fields, print all lines: 
ruby -ane '$F[0],$F[1] = $F[1],$F[0]; puts $F.join(" ")'  file.txt

# print the line preceding a regex match, not the matched line: 
ruby -ne 'print $r.to_s if ~/match/; $r = $_' file.txt

# print lines by number in a file
ruby -ne 'print if (2..4).include?($.)' file.txt

# print but remove duplicate lines
ruby -ne 'BEGIN{$a={}}; print unless $a[$_]; $a[$_] = $_'


"With a PC, I always felt limited by the software available. On Unix, I am limited only by my knowledge."
-- Peter J. Schoenster





1998-2024 Celebrazio.net
Serving AI Free since 1998.