Batch text processing is essential for refactoring, configuration updates, and code migrations. This drill teaches you to search multiple files for patterns, perform replacements, handle different file encodings, and create backup copies. You'll learn glob patterns for file matching, regular expressions, in-place file editing, and safe file operationsโessential skills for building developer tools, automation scripts, and migration utilities.
File.readlines(file) returns array of lines with newlines
Use .map(&:strip) to remove whitespace from each line
Dir.glob('**/' + pattern) searches recursively
File.file?(path) checks if path is a regular file (not directory)
string.scan(pattern).length counts occurrences
string.gsub(pattern, replacement) replaces all occurrences
Create backup: File.write(path + '.bak', content)
Sort files alphabetically: array.sort_by { |item| item[:path] }
find_and_replace('replace.txt')
FIND AND REPLACE REPORT ================================================== Search: TODO Replace: FIXME Files: *.txt -------------------------------------------------- Modified: file1.txt (2 replacements) Modified: subfolder/file3.txt (2 replacements) -------------------------------------------------- SUMMARY Files scanned: 3 Files modified: 2 Total replacements: 4
find_and_replace('replace.txt')
FIND AND REPLACE REPORT ================================================== Search: old_method Replace: new_method Files: *.rb -------------------------------------------------- Modified: lib/helper.rb (1 replacements) Modified: script1.rb (1 replacements) Modified: script2.rb (2 replacements) -------------------------------------------------- SUMMARY Files scanned: 3 Files modified: 3 Total replacements: 4
find_and_replace('replace.txt')
FIND AND REPLACE REPORT ================================================== Search: NOTFOUND Replace: REPLACEMENT Files: *.txt -------------------------------------------------- (No files modified) -------------------------------------------------- SUMMARY Files scanned: 2 Files modified: 0 Total replacements: 0
Console output will appear here...
Are you sure?
You're making great progress