51
file, _ := os.Open("x.txt")
    f := bufio.NewReader(file)

    for {
        read_line, _ := ReadString('\n')
        fmt.Print(read_line)


        // other code what work with parsed line...
        }

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
tseries
  • 723
  • 1
  • 6
  • 14
  • 4
    Please spend some time at the [help] to understand how to ask here. Not with cross tagging for example. – GhostCat Jun 09 '17 at 02:48
  • It doesn't add the newline, the newline is there in the file. From [the documentation on ReadString](https://golang.org/pkg/bufio/#Reader.ReadString), "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter." It does *exactly what it says* it will do. – Adrian Jun 09 '17 at 13:49

3 Answers3

80

You can slice off the last character:

read_line = read_line[:len(read_line)-1]

Perhaps a better approach is to use the strings library:

read_line = strings.TrimSuffix(read_line, "\n")
Alex Lew
  • 2,064
  • 14
  • 17
25

If you want to read a file line-by-line, using bufio.Scanner will be easier. Scanner won't includes endline (\n or \r\n) into the line.

file, err := os.Open("yourfile.txt")
if err != nil {
    //handle error
    return
}
defer file.Close()

s := bufio.NewScanner(file)
for s.Scan() {
    read_line := s.Text()

    // other code what work with parsed line...
}

If you want to remove endline, I suggest you to use TrimRightFunc, i.e.

read_line = strings.TrimRightFunc(read_line, func(c rune) bool {
    //In windows newline is \r\n
    return c == '\r' || c == '\n'
})

Update:
As pointed by @GwynethLlewelyn, using TrimRight will be simpler (cleaner), i.e.

 read_line = strings.TrimRight(read_line, "\r\n")

Internally, TrimRight function call TrimRightFunc, and will remove the character if it match any character given as the second argument of TrimRight.

putu
  • 6,218
  • 1
  • 21
  • 30
  • 6
    Wouldn't it be more easy just with `read_line = strings.TrimRight(read_line, "\r\n")`? – Gwyneth Llewelyn Sep 06 '17 at 11:15
  • @GwynethLlewelyn you're correct. I misunderstood the `TrimRight` function. I thought it will remove the strings if it *exactly* match the second argument. – putu Sep 06 '17 at 11:41
  • Ah, I just asked that because I'm a newbie Gopher and sometimes there are excellent reasons for doing things in a non-obvious-way. Thanks for the clarification. – Gwyneth Llewelyn Sep 12 '17 at 08:43
13

Clean and Simple Approach

You can also use the strings.TrimSpace() function which will also remove any extra trailing or leading characters like the ones of regex \n, \r and this approach is much more cleaner.

read_line = strings.TrimSpace(read_line)

Go doc: https://pkg.go.dev/strings#TrimSpace

Ayush Kumar
  • 833
  • 2
  • 13
  • 30