Skip to content

Instantly share code, notes, and snippets.

@qxxt
Created January 8, 2022 15:15
Show Gist options
  • Save qxxt/2546f36efe51728ea113209cfe7682c2 to your computer and use it in GitHub Desktop.
Save qxxt/2546f36efe51728ea113209cfe7682c2 to your computer and use it in GitHub Desktop.
Golang get the last/first n line of a bytes
// Get first 10th line
// x := trimByteLine(b, 10, false)
//
// Get last 20th line
// y := trimByteLine(b, 20, true)
func trimByteLine(b []byte, maxL int, reverse bool) []byte {
line := 0
byteLen := len(b) - 1
if reverse {
for byteLen > 0 && line < maxL {
byteLen--
if b[byteLen] == byte(10) {
line++
}
}
return b[byteLen+1:]
}
i := 0
for i <= byteLen && line < maxL {
if b[i] == byte(10) {
line++
}
i++
}
if i == byteLen {
return b
}
return b[:i-1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment