How remove \n from lines

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")

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


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.

Tags:

Parsing

Line

Go