Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Created June 30, 2016 20:29
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 tcrowe/e5aca975db52bf712a709ebe1f4b2c2e to your computer and use it in GitHub Desktop.
Save tcrowe/e5aca975db52bf712a709ebe1f4b2c2e to your computer and use it in GitHub Desktop.
search the current directory for regexp pattern matches
var fs = require('fs'),
path = require('path'),
child_process = require('child_process'),
exec = child_process.exec,
pattern = /hello/gi,
fileList,
patternMatches = [];
// recursive directory listing
exec('find ' + __dirname, function (err, stdout, stderr) {
fileList = stdout.split('\n').filter(function (item) {
// only take .txt files
return item.trim().length > 0 && path.extname(item) === '.txt';
});
// read each file
fileList.forEach(function (item) {
var fileText = fs.readFileSync(item).toString();
// split into lines
fileText.toString().split('\n').forEach(function (lineText, lineIndex) {
// check the pattern
if (pattern.test(lineText) === true) {
// add it to the results
patternMatches.push({
fileName: item,
lineText: lineText,
line: lineIndex + 1
});
}
});
});
// display results
console.log('patternMatches', patternMatches);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment