You clarified your question, stating you want to remove certain characters from the contents of files in a directory. I created a straight forward way to traverse a directory (and optionally, subdirectories) and remove specified characters from the file contents. I used String#delete
like you started with. If you want to remove more advanced patterns you might want to change it to String#gsub
with regular expressions.
The example below will traverse a tmp
directory (and all subdirectories) relative to the current working directory and remove all occurrences of !
, $
, and @
inside the files found. You can of course also pass the absolute path, e.g., C:/some/dir
. Notice I do not filter on files, I assume it's all text files in there. You can of course add a file extension check if you wish.
def replace_in_files(dir, chars, subdirs=true)
Dir[dir + '/*'].each do |file|
if File.directory?(file) # Traverse inner directories if subdirs == true
replace_in_files(file, chars, subdirs) if subdirs
else # Replace file contents
replaced = File.read(file).delete(chars)
File.write(file, replaced)
end
end
end
replace_in_files('tmp', '!$@')