Created
January 17, 2017 10:51
-
-
Save crubier/3cfcd4931f9c52d93fed4c18d2edee16 to your computer and use it in GitHub Desktop.
Apply Regex to all files in directory, using node js
This file contains hidden or 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
var fs = require('fs'); | |
function readFiles(dirname, onFileContent, onError) { | |
fs.readdir(dirname, function(err, filenames) { | |
if (err) { | |
onError(err); | |
return; | |
} | |
filenames.forEach(function(filename) { | |
fs.readFile(dirname + filename, 'utf-8', function(err, content) { | |
if (err) { | |
onError(err); | |
return; | |
} | |
onFileContent(filename, content); | |
}); | |
}); | |
}); | |
} | |
readFiles('./', function(filename, content) { | |
console.log(filename); | |
// var newcontent=content.replace(/\n"\nauthor/,"\nauthor"); | |
var newcontent=content.replace(/title:\s*"([^"]*)\nauthor/,"title: \"$1\"\nauthor"); | |
fs.writeFile(filename,newcontent,{encoding:'utf8'}, | |
function(){ | |
console.log('OK '+filename); | |
}); | |
}, function(err) { | |
throw err; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment