Skip to content

Instantly share code, notes, and snippets.

@amit-y
Created February 9, 2015 22:25
Show Gist options
  • Save amit-y/94bda2a2812d800fa5b1 to your computer and use it in GitHub Desktop.
Save amit-y/94bda2a2812d800fa5b1 to your computer and use it in GitHub Desktop.
Grunt task to search and replace strings in file
module.exports = function(grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Project configuration.
grunt.initConfig({
// options for find and replace task
findreplace: {
cssfiles: {
files: [
'css/styles.css',
'css/bootstrap.css'
],
strings: [
['images/', 'img/'],
['../', '/']
]
}
}
});
/*
* Find and replace function - primarilly written to update paths in the CSS files
* With the config above, this function will find-replace in css/styles.css and css/bootstrap.css
* It will replace and instance of images/ with img/ and ../ with /
*/
grunt.registerTask('findreplace', 'find and replace strings in files', function() {
var complete = this.async();
var config = grunt.config('findreplace');
for (var c in config) {
var files = config[c].files, strings = config[c].strings;
for (var f=0, g=files.length; f < g; f++) {
if (grunt.file.isFile(files[f])) {
var content = grunt.file.read(files[f]);
for (var s=0, t=strings.length; s < t; s++) {
if (strings[s].length===2) {
var escapedstrings = strings[s][0].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var findregex = new RegExp(escapedstrings,'g');
var finds = content.match(findregex) || [];
grunt.log.writeln(files[f]+' : replacing '+strings[s][0]+' with '+strings[s][1]+' : '+finds.length+' match(es)');
content = content.replace(findregex,strings[s][1]);
}
}
grunt.file.write(files[f], content);
}
}
}
complete();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment