Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search text file using c# and display the line number and the complete line that contains the search keyword

I require help to search a text file (log file) using c# and display the line number and the complete line that contains the search keyword.

like image 249
Chitresh Avatar asked Mar 13 '10 08:03

Chitresh


People also ask

How to search for a line in a text file in C?

Create several integer variables and let them hold 0. Create a for loop and if a specific letter appears, have one of the variables equal the place in the array the character was found. Next, think of another specific character and repeat the same above until you find it.

How do I search for data in a text file?

If you'd like to always search within file contents for a specific folder, navigate to that folder in File Explorer and open the “Folder and Search Options.” On the “Search” tab, select the “Always search file names and contents” option.

How do I find a word in a string in C?

Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.


2 Answers

This is a slight modification from: http://msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
    if ( line.Contains("word") )
    {
        Console.WriteLine (counter.ToString() + ": " + line);
    }

   counter++;
}

file.Close();
like image 185
PeterM Avatar answered Oct 16 '22 16:10

PeterM


Bit late to the game on this one, but happened across this post and thought I'd add an alternative answer.

foreach (var match in File.ReadLines(@"c:\LogFile.txt")
                          .Select((text, index) => new { text, lineNumber = index+ 1 })
                          .Where(x => x.text.Contains("SEARCHWORD")))
{
    Console.WriteLine("{0}: {1}", match.lineNumber, match.text);
}

This uses:

  • File.ReadLines, which eliminates the need for a StreamReader, and it also plays nicely with LINQ's Where clause to return a filtered set of lines from a file.

  • The overload of Enumerable.Select that returns each element's index, which you can then add 1 to, to get the line number for the matching line.

Sample Input:

just a sample line
another sample line
first matching SEARCHWORD line
not a match
...here's aSEARCHWORDmatch
SEARCHWORD123
asdfasdfasdf

Output:

3: first matching SEARCHWORD line
5: ...here's aSEARCHWORDmatch
6: SEARCHWORD123
like image 41
Grant Winney Avatar answered Oct 16 '22 17:10

Grant Winney