Original post

I’m wondering how to implement line by line comparison of two text (.txt) files in golang.

For example, contents of file1:
Hello world!
Hello Bob!
Lorem ipsum

Contents of file2:
Hello world!
Not matched line
Lorem ipsum
Not matched line

As can you see, the 1st and 3rd lines are equal.

The result should be like:
file1 except file2: 2 from 3 lines are equal.
file2 except file1: 2 from 4 lines are equal.

Hey Valentyn!

So I know this won’t get you all the way to a solution to your problem, but the below code would be how you could open a file and then read it line by line. I’m not sure how you would scan two file at the same time, but you could possibly read each file into a slice of strings where each index would be a line.

Then it would be easier to work with these two []string and compare each index to each other. It’s pretty inefficient because you need to allocate two slices and then loop over them, but if it’s good enough for your use case it could work :man_shrugging:

file, err := os.Open("file1.txt")
if err != nil {
        panic(err)
}

scanner := bufio.NewScanner(file)

var file1Lines []string

for scanner.Scan() {
        currentLineText := scanner.Text()
        file1Lines = append(file1Lines, currentLineText)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.