-
-
Save vigoritodcx/9fbf2dd47ab972e4663dac54ad296e8b to your computer and use it in GitHub Desktop.
Grunt task to search and replace strings in file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(config_prop) { | |
var complete = this.async(); | |
var config = grunt.config('findreplace'); | |
for (var c in config) { | |
var files = config[c].files, strings = config[c].strings; | |
// if the argument is a specific config, we run that one | |
if(typeof config_prop !== 'undefined') { | |
files = config[config_prop].files; | |
strings = config[config_prop].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