Created
June 30, 2016 20:29
-
-
Save tcrowe/e5aca975db52bf712a709ebe1f4b2c2e to your computer and use it in GitHub Desktop.
search the current directory for regexp pattern matches
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
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