Ruby oneliners
reverse file lines:
$ ruby -e 'file.open("foo").each_line { |l| puts l.chop.reverse }'
reverse lines from stdout:
cat foo | ruby -e 'while s = gets; puts s.chop.reverse; end'
in-place file editing:
$ cat foo qwe 123 bar $ ruby -i -lpe '$_.reverse!' foo $ cat foo ewq 321 rab
indent every line:
ruby -ne 'puts " " * 4 + $_' example.rb
Delete all consecutive blank lines from file except the first one in each group:
ruby -ne 'puts $_ if /^[^\n]/../^$/'
Extract all comments (marked with */…*/):
ruby -ne 'puts $_ if ($_ =~ /^\/\*/)..($_ =~ /\*\/$/)' comments.txt
Alternative Extract all comments (marked with */…*/):
ruby -pe 'next unless ($_ =~ /^\/\*/)..($_ =~ /\*\/$/)' comments.txt
Highlight trailing spaces:
ruby -lpe '$_.gsub! /(\s+)$/, "\e[41m\\1\e[0m"' example.rb
Remove trailing spaces:
ruby -lpe '$_.rstrip!' example.rb
Highlights with red the part of it that goes over 50 characters:
ruby -ne 'puts "#{$_}\e[31m#{$_.chop!.slice!(60..-1)}\e[0m"' example.rb
ruby -e 'w = $*.shift; $<.each { |l| puts "#{l}\e[31m#{l.chop!.slice!(w.to_i..-1)}\e[0m" }' 50 example.rb
See ruby compilation flags
ruby -r rbconfig -e 'puts RbConfig::CONFIG["configure_args"]'
Print RPM dependencies
ruby -e 'puts $(rpmdep glibc).split(",")[2..-1]'
Line numbering (per file file):
ruby -ne '$. = 1 if $<.pos - $_.size == 0; puts "#$. #$_"' foo.rb bar.rb
Count words:
ruby -ane 'w = (w || 0) + $F.size; END { p w }' exmpl.txt
Line numbering (all files at once):
ruby -ne 'puts "#$. #$_"' foo.rb bar.rb