Home > Back-end >  Filter text file between two dates
Filter text file between two dates

Time:12-09

So I have a text file test.txt with lines similar to:

08/12/2021 
test1
test2
test3
... (some entries)
12/12/2021 
test21
test22
test23
... (some entries)
24/12/2021

What should I to write next in order to filter the text file to get the lines between the two newest dates??

const fs = require('fs');
fs.watchFile('test.txt', (eventType, filename) => {
  fs.readFile('test.txt', 'utf-8', (err, data) => {
      const arr = data.toString().replace(/\r\n/g,'\n').split('\n');
  ...

The output will be something such as:

test21
test22
test23
... (some entries)

Which are the entries between the two newest dates.

Update: The text file is actually constantly writing in entries and will input the current date at the end of the day. Which now I am trying to extract the entries between the previous and newest date for further process

CodePudding user response:

I don't know about javascript but it seems you are looking like this one Is there any way to find data between two dates which are presend in same string and store it to json object

CodePudding user response:

You can do one thing, find the indexOf start date and end date then you can slice the contents. You can do something like this:

try {
const data = fs.readFileSync('test.txt', {encoding:'utf8', flag:'r'}),
      start = data.indexOf('start date'),
      end = data.lastIndexOf('end data');

const trimText = data.slice(start, end);

} catch(e) {
  console.log(e)
}

This method will work well for small file if the file is large we need to read it asynchronously and check for the start and end date while reading it.

CodePudding user response:

const test_data = `08/12/2021
test0
test2
test3
12/12/2021`;

console.log(
  test_data.split(/\d \/\d \/\d \n?/g).slice(1, -1)
);

  • Related