From time to time I find myself needing to replace certain strings globally (eg: in a directory tree), or deleting lines based on a match. I find sed extremely annoying and I don’t manage to get around its syntax. So ruby comes in handy!
replacer.rb
exp_search = '<%=launchBean\.getCustomVersion\(\)%>' exp_replace = '${xsession.info.launchBean.customVersion}' directory = '**/' file_mask = '*.jsp' Dir.glob(directory+file_mask).each do |file| File.open(file, 'r+') do |f| content = f.read if /#{exp_search}/ =~ content s = content.gsub(/#{exp_search}/, exp_replace) f.rewind f.write s puts "#{file}: #{content.split(/#{exp_search}/).size-1} matches" end end end
deleter.rb
exp_search = 'useBean.*launchBean' directory = '**/' file_mask = '*.jsp' Dir.glob(directory+file_mask).each do |file| count = 0 content = "" File.open(file, 'r+') do |f| while line = f.gets if /#{exp_search}/ =~ line count += 1 else content = content << line end end end if count > 0 File.open(file, 'w') do |f| f.write content puts "#{file}: #{count} lines deleted" end end end
These commands are especially useful if you have to refactor a codebase that doesn’t provide direct support with refactoring tools. In this case, I was refactoring a few hundred JSPs of a legacy system.
Credits to RSF & Ruby One-Liners for most of the code & ideas. rcscript seems to be a bit too much for me at this time, I’m perfectly happy modifying replacer.rb and deleter.rb when I need it.