Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for a Specific Word in a Text File and Displaying the line its on

Tags:

c#

text-files

I am having trouble attempting to find words in a text file in C#.

I want to find the word that is input into the console then display the entire line that the word was found on in the console.

In my text file I have:

Stephen Haren,December,9,4055551235

Laura Clausing,January,23,4054447788

William Connor,December,13,123456789

Kara Marie,October,23,1593574862

Audrey Carrit,January,16,1684527548

Sebastian Baker,October,23,9184569876

So if I input "December" I want it to display "Stephen Haren,December,9,4055551235" and "William Connor,December,13,123456789" .

I thought about using substrings but I figured there had to be a simpler way.

My Code After Given Answer:

using System;
using System.IO;
class ReadFriendRecords
{
    public static void Main()
    {
        //the path of the file
        FileStream inFile = new FileStream(@"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(inFile);
        string record;
        string input;
        Console.Write("Enter Friend's Birth Month >> ");
        input = Console.ReadLine();
        try
        {
            //the program reads the record and displays it on the screen
            record = reader.ReadLine();
            while (record != null)
            {
                if (record.Contains(input))
                {
                    Console.WriteLine(record);
                }
                    record = reader.ReadLine();
            }
        }
        finally
        {
            //after the record is done being read, the progam closes
            reader.Close();
            inFile.Close();
        }
        Console.ReadLine();
    }
}
like image 777
Evan Manning Avatar asked Oct 21 '15 14:10

Evan Manning


People also ask

How do I find a specific word in a text file?

To open the Find pane from the Edit View, press Ctrl+F, or click Home > Find. Find text by typing it in the Search the document for… box. Word Web App starts searching as soon as you start typing.

How do you search for a word on a line?

Press Ctrl+F. Word displays the Navigation task pane at the left side of the screen. In the box at the top of the Navigation pane, enter the text for which you want to search. To search for a paragraph mark, enter ^p; to search for a line break, enter ^l.

How to search for a particular text in a file in Linux?

If you have a file opened in nano and need to find a particular string, there's no need to exit the file and use grep on it. Just press Ctrl + W on your keyboard, type the search string, and hit Enter .

How to check for word in text file in c#?

string text= File. ReadAllText(fileName); var result = text. Split('\n').


3 Answers

Iterate through all the lines (StreamReader, File.ReadAllLines, etc.) and check if line.Contains("December") (replace "December" with the user input).

Edit: I would go with the StreamReader in case you have large files. And use the IndexOf-Example from @Matias Cicero instead of contains for case insensitive.

Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
    while (!sr.EndOfStream) {
        var line = sr.ReadLine();
        if (String.IsNullOrEmpty(line)) continue;
        if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
            Console.WriteLine(line);
        }
    }
}
like image 178
Camo Avatar answered Oct 23 '22 03:10

Camo


As mantioned by @Rinecamo, try this code:

string toSearch = Console.ReadLine().Trim();

In this codeline, you'll be able to read user input and store it in a line, then iterate for each line:

foreach (string  line in System.IO.File.ReadAllLines(FILEPATH))
{
    if(line.Contains(toSearch))
        Console.WriteLine(line);
}

Replace FILEPATH with the absolute or relative path, e.g. ".\file2Read.txt".

like image 21
insilenzio Avatar answered Oct 23 '22 04:10

insilenzio


How about something like this:

//We read all the lines from the file
IEnumerable<string> lines = File.ReadAllLines("your_file.txt");

//We read the input from the user
Console.Write("Enter the word to search: ");
string input = Console.ReadLine().Trim();

//We identify the matches. If the input is empty, then we return no matches at all
IEnumerable<string> matches = !String.IsNullOrEmpty(input)
                              ? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
                              : Enumerable.Empty<string>();

//If there are matches, we output them. If there are not, we show an informative message
Console.WriteLine(matches.Any()
                  ? String.Format("Matches:\n> {0}", String.Join("\n> ", matches))
                  : "There were no matches");

This approach is simple and easy to read, it uses LINQ and String.IndexOf instead of String.Contains so we can do a case insensitive search.

like image 4
Matias Cicero Avatar answered Oct 23 '22 02:10

Matias Cicero