Video Coming Soon...
39: head and tail
This exercise is pending. Quick notes about this exercise:
- My implemention is at https://lcthw.dev/go/go-coreutils
- https://www.gnu.org/software/coreutils/manual/html_node/head-invocation.html
- https://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html
- https://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html
- slices -- https://pkg.go.dev/slices@go1.25.3
- strings -- https://pkg.go.dev/strings@go1.25.3
The head Code
View Source file go-coreutils/head/main.go Only
package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func HeadFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
for cur_line := 0; scan.Scan(); cur_line++ {
line := scan.Text()
if cur_line < count {
fmt.Println(line)
}
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
}
func main() {
var count int
flag.IntVar(&count, "n", 10, "number of lines")
flag.Parse()
if flag.NArg() > 0 {
files := flag.Args()
for _, fname := range files {
file, err := os.Open(fname)
if err != nil { log.Fatal(err) }
HeadFile(file, count)
}
} else {
HeadFile(os.Stdin, count)
}
}
The tail Code
View Source file go-coreutils/tail/main.go Only
package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func TailFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
var lines []string
for scan.Scan() {
lines = append(lines, scan.Text())
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
start := len(lines) - count
if start < 0 { start = 0 }
for line := int(start); line < len(lines); line++ {
fmt.Println(lines[line])
}
}
func main() {
var count int
flag.IntVar(&count, "n", 10, "number of lines")
flag.Parse()
if flag.NArg() > 0 {
files := flag.Args()
for _, fname := range files {
file, err := os.Open(fname)
if err != nil { log.Fatal(err) }
TailFile(file, count)
}
} else {
TailFile(os.Stdin, count)
}
}
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.