0

I will read a file and search for a string in it. and also which line number to find string

here is code

fs.readFile('input.txt', "utf-8", function(err, data) {
            if (err) throw err;
            console.log(data)
        }

How to find string and line number

input.txt

  1. my
  2. name
  3. is
  4. Arjun

output: line number, string
4, Arjun

Om Choudhary
  • 492
  • 1
  • 7
  • 27
Arvind kumar
  • 87
  • 2
  • 8
  • 1
    You could check this https://stackoverflow.com/questions/6831918/node-js-read-a-text-file-into-an-array-each-line-an-item-in-the-array. This will help you with the reading part. While you reading it line by line you could check if the current line contains the string you are looking for. – Christos Dec 11 '19 at 10:39
  • @Christos thanx for sharing the answer – Arvind kumar Dec 11 '19 at 10:45
  • You are very welcome. – Christos Dec 11 '19 at 11:09

2 Answers2

0

Try this code that can help you:

fs.readFile(FILE_LOCATION, function (err, data) {
 if (err) throw err;
 if(data.includes('search string')){
console.log(data)
}
});
Marwen Jaffel
  • 703
  • 1
  • 6
  • 14
0

Try a for loop:

const searchStr = 'aSearchTerm';
const lineArray = fs.readFileSync('file.txt').toString().split('\n');
for (const line of lineArray) {
    const lineNumber = line.split(/[\s.]+/)[0]; // regular expression (regex)
    const searchComponent = line.split(/[\s.]+/).slice(-1)[0]; // regex
    if (searchComponent === searchStr) {
        console.log(lineNumber.concat(', ', searchComponent))
        break;
    }
}

Learn about JS array operations

Learn about JS string operations

What are regular expressions?

wfunston
  • 96
  • 1
  • 4