Decker
Decker

Reputation: 79

How check whether a file contains a string or not?

I've tried to search on Google for pattern matching function between file and string but I could not find it. I've also tried to use strings.Contains(), but it gives wrong result in large input file.

Is there any function in Go for searching string in some file?

If no, is there another way to resolve this problem?

Here is my code:

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func main() {

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')

    // read the whole file at once

    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    s := string(b)
    length := len(s)

    //check whether s contains substring text
    fmt.Println(strings.Contains(s, text))

}

Upvotes: 2

Views: 17845

Answers (2)

Jasmit Tarang
Jasmit Tarang

Reputation: 135

I am just adding a flag to use command line arguments. If nothing is passed it will prompt you :).

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "strings"
)

//Usage go run filename -text=dataYouAreLookingfor
//if looking for Nissan in file the command will be
// go run filename -text=Nissan

func main() {
    var text string
    // use it as cmdline argument
    textArg := flag.String("text", "", "Text to search for")
    flag.Parse()
    // if cmdline arg was not passed ask
    if fmt.Sprintf("%s", *textArg) == "" {
        fmt.Print("Enter text: ")
        // get the sub string to search from the user
        fmt.Scanln(&text)
    } else {
        text = fmt.Sprintf("%s", *textArg)
    }
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }
    s := string(b)
    // //check whether s contains substring text
    fmt.Println(strings.Contains(s, text))
}

Upvotes: 1

InkyDigits
InkyDigits

Reputation: 3228

If I read your question correctly you want to read from a file and determine if a string entered at the command line is in that file... And I think the problem that you are seeing has to do with the string delimiter, the reader.ReadString('\n') bit, and not string.Contains().

In my opinion it will be a little bit easier to make what you want work with fmt.Scanln; it will simplify things and will return a result that I'm pretty sure is what you want. Try this variation of your code:

package main

import (
    "fmt"
    "io/ioutil"
    "strings"
)

func main() {
    var text string
    fmt.Print("Enter text: ")
    // get the sub string to search from the user
    fmt.Scanln(&text)

    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }
    s := string(b)
    // //check whether s contains substring text
    fmt.Println(strings.Contains(s, text))
}

Upvotes: 9

Related Questions