如何打印包含特定string的行?
我想在string中打印包含date的行,我正在使用拆分模块来实现该任务。 下面的代码总是打印else语句。
ctrl.js
fs.readFile(dir + '/' + logFile, 'utf8', function(err, data) { var lines = data.split('\n'); var linesWithDate = lines.split('|')[0].replace(/[\[\]']+/g,''); lines.forEach(function(line) { if (linesWithDate) { console.log('print lines with date',line); } else { console.log('print lines without date',line); } } });
文件数据
[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy [2017-03-23T19:20:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum
如何打印包含特定string的行?
const split = require('split'); fs.createReadtStream(path.join(dir, logFile), 'utf8') .pipe(split()).on('data', (line) => { if (line.indexOf('string') > -1) { console.log('Line with string:', line); } else { console.log('Line without string:', line); } });
我想打印行中包含date的string,我正在使用拆分模块来实现该任务。 下面的代码总是打印else语句
我不认为你正在使用split
模块。 这个例子确实:
const split = require('split'); const regex = require('regex-iso-date'); fs.createReadtStream(path.join(dir, logFile), 'utf8') .pipe(split()).on('data', (line) => { if (regex().test(line)) { console.log('Line with date:', line); } else { console.log('Line without date:', line); } });
请注意,这不一定是一个有效的date,因为它可能匹配date如2017年1月13日… – testing有效date只看到这个答案:
- 检查一个string是否是一个date值
或者如果你想匹配你的特定的string,如[2017-03-23T18:13:16Z]
那么你可以尝试这样的事情:
const split = require('split'); const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/; fs.createReadtStream(path.join(dir, logFile), 'utf8') .pipe(split()).on('data', (line) => { if (regex.test(line)) { console.log('Line with date:', line); } else { console.log('Line without date:', line); } });
请注意,如果您的文件中包含这些date,它也将与无效的date匹配。
这是一些代码,只打印出有效的parsingdate,按行。 我使用readline模块而不是readfile,但是您应该能够通过replaceinput: process.stdin
:'use strict'来轻松调整逻辑。
var sExample = '[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum'; const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.setPrompt('Enter example string to test > '); rl.prompt(); rl.on('line', (line) => { var sCandidate = line.split('|')[0].replace(/[\[\]']+/g,''); if (Date.parse(sCandidate)) { //it is a valid date console.log(sCandidate); } process.exit(0); });