Created
January 8, 2022 15:15
-
-
Save qxxt/2546f36efe51728ea113209cfe7682c2 to your computer and use it in GitHub Desktop.
Golang get the last/first n line of a bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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