Skip to content

Instantly share code, notes, and snippets.

@ColinOrr
Created July 24, 2013 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ColinOrr/6069564 to your computer and use it in GitHub Desktop.
Save ColinOrr/6069564 to your computer and use it in GitHub Desktop.
Global find and replace for file names, folders and contents.
# Placeholders
PROJECT = /_Project_/
COMPANY = /_Company_/
PROJECT_LOWER = /_project_/
# Recursively replaces all placeholders in file names, folders and content
def rename(project, company)
renameFiles('.', project, company)
replaceContent('**/*', project, company)
end
# Recursively replaces all placeholders in file names and folders
def renameFiles(folder, project, company)
Dir.chdir(folder) do
# Rename all of the files & folders
Dir.glob('*').each do |path|
if containsPlaceholder path
newPath = replacePlaceholders(path, project, company)
File.rename path, newPath
puts "renamed:\t#{newPath}"
end
end
# Recurse into subfolders
Dir.glob('*/').each do |subfolder|
renameFiles(subfolder, project, company)
end
end
end
# Replaces all placeholders in the files matching the specified pattern
def replaceContent(pattern, project, company)
Dir.glob(pattern).each do |path|
if File.file? path
content = File.read(path)
if containsPlaceholder content
content = replacePlaceholders(content, project, company)
File.open(path, 'w+') { |f| f.write(content) }
puts "modified:\t#{path}"
end
end
end
end
# Determines if a string contains any of the placeholders
def containsPlaceholder(value)
value.match PROJECT or
value.match COMPANY or
value.match PROJECT_LOWER
end
# Replaces the placeholders in a string
def replacePlaceholders(value, project, company)
value
.gsub(PROJECT, project)
.gsub(COMPANY, company)
.gsub(PROJECT_LOWER, project.downcase)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment